0

I have a set of checkboxes in an HTML file. Then I have onClick() event handlers in two separate JavaScript files. I just noticed that only one of of my onClick methods is being called when I click on the checkboxes. If I remove one of the event handlers then then other one will work. There must be some way to get a click event and not swallow the event for other listeners.

How do I allow both of the event handlers to be called?

        var at = document.getElementById("at");
        at.onclick = function() { 
ad absurdum
  • 17,836
  • 5
  • 33
  • 54
user3470688
  • 529
  • 6
  • 19
  • that is because your first callback is being replaced by the last one. you should see @chiliNUT 's answer, and also you should probably also see this http://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick – Paul John Diwa Jan 09 '17 at 07:54

1 Answers1

0

Assigning to onclick will overwrite whatever was there before. If you want to stack events, Use addEventListener in native JS or jQuery .on("click"

JS

var at = document.getElementById("at");
at.addEventListener("click", function() { //whatever
                                        }, false);
at.addEventListener("click", function() { //some other function
                                        }, false);

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

jQuery

$('#at').on("click", function() {//whatever
                                })
        .on("click", function() {//some other function
                                });

http://api.jquery.com/on/

chiliNUT
  • 17,890
  • 12
  • 63
  • 99
  • 1
    Indeed. Also, if you want to stop event execution from some onclick event, you can call `event.stopPropagation()` [https://api.jquery.com/event.stoppropagation/](https://api.jquery.com/event.stoppropagation/) – Valijon Jan 09 '17 at 01:00