Is it possible to use two .onclick event handlers on the same button when the event handlers are stored in two different scripts? I know it would be easy to just call the two functions I need into the same .onclick handler, but I'm curious if there's a way around this.
Suppose I have
script1.js
someButton.onclick = function() {
someFunction1();
}
script2.js
someButton.onclick = function() {
someFunction2();
}
Running these scripts in the html in this order would lead to calling someFunction2() onclick, as I assume the functionality of the button is overwritten by script2.js.
You can use addEventListener and this will add both the event handlers to the element on contrast to replacing the onclick attribute of the element.
someButton.addEventListener('click', function() {
someFunction1();
});
someButton.addEventListener('click', function() {
someFunction2();
});
Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With