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>
The vast majority of browser implementations (Chrome, Firefox, Opera, etc.), including IE9, fire the handlers in the order in which they were attached. IE8 and earlier do it the other way around.
You can assign as many handlers as you want to an event using addEventListener().
The addEventListener() methodYou can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With