As you know, events usually bubble up in javascript, so the event handler of the element that fires the event is executed first, then the event handler of the parent element is called and so on. This behaviour causes some problems on a project I'm currently working on, I would rather have the execution order reversed.
I figuered out a solution that is using timeouts:
$(element).mouseover(function(){
var that = this;
setTimeout(function() {
//actual event handler, but references to "this" are replaced with "that"
},$(this).parents().length)
});
So basically, the event handlers are executed after a short timeout, the waiting time depends on the the depth of the element in the DOM-tree: The event handler of the the html-element is executed right away, the event handler of the body element is executed after waiting 1ms and so on. So the execution order of the events is reversed.
The results of my first tests are positive, but I'm still not sure if there are any problems or drawbacks with this solution. What do you think of this solution? Other ideas on how to solve this problems are also highly appreciated.
Event capturing is the opposite of bubbling (events are handled at higher levels first, then sink down to individual elements at lower levels).
stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Tip: Use the event. isPropagationStopped() method to check whether this method was called for the event.
Reverse event bubbling is called capture phase.
See the DOM event architecture
Pass true
as the 3rd argument to Event.addEventListener
to have it trigger on capture phase
el.addEventListener("click", function () {
console.log("i run in capture");
}, true);
Of course it won't work in legacy platforms. You'll need a DOM3 events shim to emulate the event system. Feel free to contribute to the DOM-shim
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