Priority when more than one event handler is bound to an element
Solution 1:
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:
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:
First come, first serve. The first one bound will be the first one triggered, and so on...
Related: jQuery event handlers always execute in order they were bound - any way around this?