The order of events in the DOM

    Faced a problem in his calendar - there are two elements, one of which is positioned absolutely on the whole screen, a translucent dimming curtain and the second is a shape. You have probably seen such solutions when displaying pictures in a lightbox or authentication on habrahab ..

    The problem is that when you click on an 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 for conveying events in an object-oriented hierarchy
    • Bubble method ( bubbling ), when the event occurs inside and then passed to the parent elements outside. MS Internet Explorer, Opera, Firefox
    • Capture the event ( capturing ), the event is processed first by the parents, and then penetrates deeper. Opera, Firefox

    The W3C consortium prudently decided that it might be convenient for developers to send events (event propagation) in any direction, therefore, according to the standard, the two models are combined - the event is first captured, and then returned as a bubble.

    Thus the developer can bind to a method called phase event: It turns out that when clicking on form_bg occurs immediately hideBackground , form on the capturing phase is not caused, then returning in bubbling phase caused doNothing .
    $('form_bg').addEventListener('click',hideBackground,true); // true - говорит о фазе capturing $('form').addEventListener('click',doNothing,false); // false - говорит о фазе bubbling

    Default tradition

    The W3C model is pleasant, but by default, most likely due to IE, the usual event registration implies a bubbling phase, i.e. inside out. And this in turn means that if I explicitly point to the parent element: Then any event without stopping causes all on-parent elements to process onclick events. Do they have it or not, right down to the root - document.$('form_bg').onclick = hideBackground; // или как выше - в div id='form_bg' onclick=..

    Bubble Free

    In a cross-browser version, to stop the distribution of event processing to the parent elements, you need to change the cancelBubble parameter to true (for IE) and call the stopPropagation function (W3C model): Now I’m interested in how the event processing model in other languages ​​and platforms works - Java, NET , Flash..Written based on the article " Event order ". + original with comments

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

    Also popular now: