1

I'm curious here, I know that it's possible to attach multiple event handlers to same element if I use DOM Level 2 method called addEventListener(), so I'm wondering if we have this situation:

someButton.addEventListener("mouseover", showHint, false);

someButton.addEventListener("mouseover", showHintTwo, false);

Is this possible in real world scenario? Example above ^

And how could I choose when I want to call showHint and when I want to call showHintTwo,is it possible to handle it/separate it somehow ... because both of the event handlers will fire when mouseover happened?

Thanks guys

Cheers

rokie12234
  • 57
  • 1
  • 10
  • Possible duplicate of [Can multiple event listeners/handlers be added to the same element using javascript?](https://stackoverflow.com/questions/5411055/can-multiple-event-listeners-handlers-be-added-to-the-same-element-using-javascr) – Cyrus Dec 24 '18 at 21:14
  • @CyrusCuenca Can multiple event listeners/handlers be added to the same element using javascript? That is not my question! I know it is possible but I'm wondering how to handle them separatedly, how to call different handler on same event whenever I want... .... – rokie12234 Dec 24 '18 at 21:17
  • I guess if there were a flag of some sorts on the button you could have a fork from where you could have two functionalities.. but then again you would not need to have two handlers.. Instead a simple if else would allow you to figure out what to do when... – bullettrain Dec 24 '18 at 21:21

2 Answers2

1

Like this? https://codepen.io/cyruscuenca/pen/xmrxob

It doesn't make much sense, but it satisfies what you want.

  • 2 event handlers.
  • You can choose to which block is actually shown with the toggle.

I would personally add one event handler and pass in a condition like:

document.getElementById("btn").addEventListener("click", function(condition) {
    switch(condition) {
      case x:
      // code block
      break;
    case y:
      // code block
      break;
    default:
      // code block
  } 
});
Cyrus
  • 613
  • 1
  • 6
  • 22
0

A good way to handle this would be to create a separate hint counter variable and then show the relevant hint of your choice. How you want to update the counter will determine when which hint will be shown.

let hintCounter = 1;

function showHint() {
    switch(hintCounter) {
        case 1: // show first hint
        case 2: // show second hint
    }

    hintCounter++;
}

someButton.addEventListener("mouseover", showHint, false);

If you need to set the second hint to show after a set amount of time, take a look at the setTimeout() function in JS.

tripathiakshit
  • 624
  • 5
  • 17