Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  177] [ 7]  / answers: 1 / hits: 72131  / 13 Years ago, tue, january 24, 2012, 12:00:00

Can someone explain me why is there a difference in the order in which the event handlers are being executed depending on how they have been attached? In the example below I'm using the .on() and .addEventListener() methods to handle a specific event on different DOM elements.



jsfiddle: http://jsfiddle.net/etsS2/



I thought that in this particular example the order in which the event handlers are going to be executed will depend on the event-bubbling - so starting from the original event target and moving up to the document element.



document.getElementById('outer').addEventListener('mouseup', function (event) {
//$('#outer').on('mouseup', function (event) {
alert('This alert should not show up!');
}, false);


If I uncomment the on(); version everything works as expected - is there a difference in how jQuery handles events contrary to plain JavaScript?


More From » jquery

 Answers
14

When you use .on() at the document level, you're waiting for the event to bubble all the way up to that point. The event handler for any intermediate container will already have been called.



Event bubbling is the process by which the browser looks for event handlers registered with parents of the element that was the actual original recipient of the event. It works upwards in the DOM tree. The document level is the last level checked. Thus, your handler registered with .on() won't run until that level is reached. In the meantime, the other event handler at the outer level is reached first and it is executed by the browser.



Thus, that return false; in the handler registered with .on() is pretty much useless, as would be a call to event.stopPropagation(). Beyond that, mixing native event handler registration with the work that a library like jQuery will do is probably a really bad idea unless you seriously know what you're doing.



There was a question asked almost exactly like this one just a little while ago today.


[#87822] Monday, January 23, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trentb

Total Points: 261
Total Questions: 101
Total Answers: 90

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
trentb questions
Sat, Mar 27, 21, 00:00, 3 Years ago
Fri, Feb 26, 21, 00:00, 3 Years ago
Thu, Sep 24, 20, 00:00, 4 Years ago
;