Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anyway to use two .onclick event handlers from two different scripts on one button?

Tags:

javascript

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.

like image 220
stefvhuynh Avatar asked Dec 11 '25 05:12

stefvhuynh


1 Answers

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

like image 182
PSL Avatar answered Dec 13 '25 19:12

PSL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!