Okay, I have a button element in my web application.
<button id="mybutton">My Button</button>
When clicked on an event listener triggers a function
document.getElementById('mybutton').addEventListener('click',myFunction, false);
myFunction() {
console.log('myFunction called');
}
However, when my button is clicked, I don’t need it to call that same function again. However, it would simplyfy my code if I could have another event listener calling a different function, or perhaps the same event listener calling a different function.
document.getElementById('mybutton').addEventListener('click',myFunction2, false);
myFunction2() {
console.log('myFunction2 called');
}
Now I believe, previously, it was possible to change the function of a button by changing the onclick event attribute using JavaScript. However, I believe that using onclick event attributes now go against Firefox and Chrom policies.
I have tried just having my event listener calling the function and then a new event listener in that function to see if it would override the first event listener, but it seems that the first event listener will continue listening.
2
Answers
They are widely considered to be bad practise, but I don’t believe either browser vendor has a stated policy about them.
This is one of the advantages of
addEventListener
. I wrote some relatively complex code in the 90s to add new event listeners while preserving existing ones. I’m happy not to need to do that now.For that specific case, you can specify that an event listener should be called only once (there is an option for it that you can pass to
addEventListener
) andstopImmediatePropagation
will prevent the second function being called on the first click.For other cases, you could make use of
removeEventListener
or define a boolean variable that you set totrue
when you want different behaviour from a function.There’s no need in multiple event handlers in your case imho.
Is it possible to select which function to execute with a finite state machine with just 1 event listener. You can chain any number of functions that way:
A simplified version: