Priority when more than one event handler is bound to an element

Jquery

Jquery Problem Overview


When more than one event handler is bound to an element, how is it determined which one is triggered first?

<script> 
$(function(){
    $(".li").find('input').click(function(){alert('li>input');});
    $(".li").click(function(){alert('li');});
    $('input').click(function(){alert('input');});
});
</script>
</head>

<body>
<ul>
<li class="li"><input type="checkbox" /><span>Hello</span></li>
<li class="li"><input type="checkbox" /><span>Hello</span></li>
<li class="li"><input type="checkbox" /><span>Hello</span></li>
</ul>
</body>

Jquery Solutions


Solution 1 - Jquery

I want to point out that the "First come, first serve" rule is not always true, it also depends on how you register a handler:

Handler1 - $(document).on('click', 'a', function....)
Handler2 - $('a').on('click', function....)

This the above example, the Handler 2 is always called before the handler1.

Have a look at this fiddle: http://jsfiddle.net/MFec6/

Solution 2 - Jquery

If two event handlers are bound to the exact same object, it would be first come, first serve. The first one attached will execute first.

But, your example looks a bit different. It looks like you also have one event bound to the input object and others to the parent li object. In that case, the one where the event actually originated (presumably the input element in this case) will occur first and then the event will bubble up to the parent objects and they will occur later.

If you want to stop the bubbling up to the parents, you can use jQuery's event.stopPropagation() and the event will not reach the parents and never trigger their event handlers. That would look like this:

$('input').click(function(e) {
    e.stopPropagation();
    alert('input');
});

Per the jQuery documentation for stopPropagation(), it does not stop other event handlers on the same object, only event handlers on parent objects that would normally get the event via bubbling up the parent tree.

You can see the difference here: http://jsfiddle.net/jfriend00/L33aq/

Solution 3 - Jquery

First come, first serve. The first one bound will be the first one triggered, and so on...

Related: https://stackoverflow.com/questions/2360655/jquery-event-handlers-always-execute-in-order-they-were-bound-any-way-around-t

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
Questionuser1032531View Question on Stackoverflow
Solution 1 - JqueryDavid LinView Answer on Stackoverflow
Solution 2 - Jqueryjfriend00View Answer on Stackoverflow
Solution 3 - Jquerykarim79View Answer on Stackoverflow