Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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> 
like image 972
user1032531 Avatar asked Jan 08 '12 17:01

user1032531


People also ask

In what order multiple handlers fired?

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.

Can you have multiple event handlers?

You can assign as many handlers as you want to an event using addEventListener().

Can you add multiple event listeners to an element?

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.


1 Answers

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/

like image 130
David Lin Avatar answered Sep 21 '22 09:09

David Lin