📜 ⬆️ ⬇️

DOM event execution order

I faced a problem in my calendar - there are two elements, one of which is positioned absolutely on the whole screen, a translucent blackout curtain and the second - a form. You must have seen such solutions when displaying pictures in a lightbox or authentification on habrahabr ..






The problem is that with any click on the internal element, the event is automatically called on the parent element. This made me think about both the solution and the theory of how browsers work.
')

Two and a half models



As it turns out, there are two models of event transmission in the object-oriented hierarchy.

The W3C consortium wisely decided that developers could be comfortable sending events (event propagation) in any direction, so according to the standard, two models are combined - the event is captured first and then returned as a bubble.


Thus, the developer can bind the called method to the event phase:
$('form_bg').addEventListener('click',hideBackground,true); // true - capturing $('form').addEventListener('click',doNothing,false); // false - bubbling



It turns out that when you click on form_bg , hideBackground occurs immediately, the form is not called on the capturing phase, then returning, in the bubbling phase, doNothing is called .


Traditions by default

The W3C model is pleasant, but by default, it seems that due to IE, normal event registration implies a bubbling phase, i.e. from the inside out. And this in turn means that if I explicitly point to the parent element: $('form_bg').onclick = hideBackground; // - div id='form_bg' onclick=..
$('form_bg').onclick = hideBackground; // - div id='form_bg' onclick=..


Then any event without stopping causes onclick-event processing for all parent elements. Whether they have it or not, right down to the root - document.

Swim without bubbles

In a cross-browser version, in order to stop the propagation of event handling to the parent elements, you must change the cancelBubble parameter to true (for IE) and call the stopPropagation function (W3C model):

function hideBackground(e){
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}


Now I am wondering how the event handling model is organized in other languages ​​and platforms - Java, NET, Flash..It is written based on the article " Event order ".

+ original with comments

Source: https://habr.com/ru/post/22142/


All Articles