jQuery: more than one handler for same event

JavascriptJqueryEvent Handling

Javascript Problem Overview


What happens if I bind two event handlers to the same event for the same element?

For example:

var elem = $("...")
elem.click(...);
elem.click(...);

Does the last handler "win", or will both handlers be run?

Javascript Solutions


Solution 1 - Javascript

Both handlers will run, the jQuery event model allows multiple handlers on one element, therefore a later handler does not override an older handler.

The handlers will execute in the order in which they were bound.

Solution 2 - Javascript

Suppose that you have two handlers, f and g, and want to make sure that they are executed in a known and fixed order, then just encapsulate them:

$("...").click(function(event){
  f(event);
  g(event);
});

In this way there is (from the perspective of jQuery) only one handler, which calls f and g in the specified order.

Solution 3 - Javascript

jQuery's .bind() fires in the order it was bound:

> When an event reaches an element, all handlers bound to that event > type for the element are fired. If there are multiple handlers > registered, they will always execute in the order in which they were > bound. After all handlers have executed, the event continues along the > normal event propagation path.

Source: http://api.jquery.com/bind/

Because jQuery's other functions (ex. .click()) are shortcuts for .bind('click', handler), I would guess that they are also triggered in the order they are bound.

Solution 4 - Javascript

You should be able to use chaining to execute the events in sequence, e.g.:

$('#target')
  .bind('click',function(event) {
    alert('Hello!');
  })
  .bind('click',function(event) {
    alert('Hello again!');
  })
  .bind('click',function(event) {
    alert('Hello yet again!');
  });

I guess the below code is doing the same

$('#target')
      .click(function(event) {
        alert('Hello!');
      })
      .click(function(event) {
        alert('Hello again!');
      })
      .click(function(event) {
        alert('Hello yet again!');
      });

Source: http://www.peachpit.com/articles/article.aspx?p=1371947&seqNum=3

TFM also says:

> When an event reaches an element, all handlers bound to that event > type for the element are fired. If there are multiple handlers > registered, they will always execute in the order in which they were > bound. After all handlers have executed, the event continues along the > normal event propagation path.

Solution 5 - Javascript

Both handlers get called.

You may be thinking of inline event binding (eg "onclick=..."), where a big drawback is only one handler may be set for an event.

jQuery conforms to the DOM Level 2 event registration model:

> The DOM Event Model allows > registration of multiple event > listeners on a single EventTarget. To > achieve this, event listeners are no > longer stored as attribute values

Solution 6 - Javascript

Made it work successfully using the 2 methods: Stephan202's encapsulation and multiple event listeners. I have 3 search tabs, let's define their input text id's in an Array:

var ids = new Array("searchtab1", "searchtab2", "searchtab3");

When the content of searchtab1 changes, I want to update searchtab2 and searchtab3. Did it this way for encapsulation:

for (var i in ids) {
    $("#" + ids[i]).change(function() {
        for (var j in ids) {
            if (this != ids[j]) {
                $("#" + ids[j]).val($(this).val());
            }
        }
    });
}

Multiple event listeners:

for (var i in ids) {
    for (var j in ids) {
        if (ids[i] != ids[j]) {
            $("#" + ids[i]).change(function() {
                $("#" + ids[j]).val($(this).val());
            });
        }
    }
}

I like both methods, but the programmer chose encapsulation, however multiple event listeners worked also. We used Chrome to test it.

Solution 7 - Javascript

There is a workaround to guarantee that one handler happens after another: attach the second handler to a containing element and let the event bubble up. In the handler attached to the container, you can look at event.target and do something if it's the one you're interested in.

Crude, maybe, but it definitely should work.

Solution 8 - Javascript

jquery will execute both handler since it allows multiple event handlers. I have created sample code. You can try it

demo

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionflybywireView Question on Stackoverflow
Solution 1 - JavascriptRuss CamView Answer on Stackoverflow
Solution 2 - JavascriptStephan202View Answer on Stackoverflow
Solution 3 - JavascriptallicarnView Answer on Stackoverflow
Solution 4 - JavascriptanddoutoiView Answer on Stackoverflow
Solution 5 - JavascriptCrescent FreshView Answer on Stackoverflow
Solution 6 - JavascriptGeneralElektrixView Answer on Stackoverflow
Solution 7 - JavascriptDavidView Answer on Stackoverflow
Solution 8 - JavascriptVikram RajputView Answer on Stackoverflow