Event bubbling in JavaScript? Explanation of event propagation

Source: Internet
Author: User
Tags event listener

Note: The source of this article is translatable web


Event bubbling is a term you encounter while learning JavaScript, which involves invoking the order of event processing when one element is nested by another, and two elements registering the same event (for example, a click event).

But event bubbling is only part of the puzzle. It is often mentioned along with event capture and event propagation, and a deep understanding of these three concepts is essential for learning JavaScript events, for example, if you want to implement event delegation.

In this article, I'll explain these terms and show how they're grouped together. I'll also show you how to get a basic understanding of the JavaScript event flow to give you granular control over your application. Please note that this is not an introductory event, so we assume familiarity with this topic. If you want more information about the event, why not check out our books? : JavaScript: Ninja cheats. What is event propagation?

Let's start with the event propagation first. This is the generic term for event bubbling and event capture. Consider a typical tag to build a linked image list, such as a thumbnail gallery:

1 <ul>2     <Li><a href="..."><img src="..." alt=""></a>3     <Li><a href="..."><img src="..." alt=""></a>4...5     <Li><a href="..."><img src="..." alt=""></a>6 </ul>

Clicking on an image not only generates a click event for the corresponding IMG element, but also generates a click event for the parent element, grandparent element, and so on, all the way through the ancestor element of all elements, before the Window object terminates.

In the DOM term, the image is the event target and clicks on the innermost element. The event target, along with its ancestors, from its parent element to the Window object, forms a branch in the DOM tree. For example, in an image library, the branch is made up of nodes: Img,a,li,ul,body,html,document,window.

Note that the window is not actually a DOM node, but it implements the Eventtarget interface, so for simplicity we are working on it as if it were the parent of the Document object.

This branch is important because it is the path of the event propagation (or flow). This propagation is the process of invoking all listeners of a given event type, attached to a node on the branch. Each listener is called an event object that collects information related to the event (later).

Keep in mind that multiple listeners can be registered on a node of the same event type. When propagation reaches one such node, the listener is called in the order in which it is registered.

Also note that the branch is determined to be static, that is, it was established when the event was initially dispatched. Changes made to the tree during event processing are ignored.

Event propagation is bidirectional, from window to event target, and then reversed. This communication can be divided into three stages:

    1. Parent node from window to event target: This is the capture phase
    2. Event Target itself: This is the target stage
    3. From the parent node of the event target back to window: bubbling phase

These stages can be distinguished by invoking the type of listener. Event Capture Phase

This phase only invokes the capture Listener, that is, when the listener registers, the third parameter of AddEventListener uses the true value:

  1 el.addeventlistener (' Click ', Listener, True)

If this parameter defaults to the default value false , the event listener is not the catch.

Therefore, at this stage, only the capture from window to the event target path is called. Event Target Phase

All listeners registered to the event target at this stage will be called, regardless of the value of the capture flag.

Event bubbling Phase

Only listeners that are not the receiver are called during the event bubbling phase. That is, the addEventListener() third parameter is when the listener is called to register false .

  1false//listener doesn ' t capture  2//listener doesn ' t capture

Note that all events, such as focus ,, and blur load so forth, flow down the event target during the capture phase without bubbling. This process will end after the target phase.

Therefore, at the end of the propagation, all listeners on this branch are determined to be called once.

Event bubbling does not occur on every type of event. During propagation, the listener can event .bubbles obtain whether an event will bubble by reading the object's Boolean property.

The three event flow stages are described in detail in the uievents specification.

Copyright 20.16 million Network Alliance (MIT, ERCIM, Keio, Beihang) .



Access to dissemination information

I mentioned event the properties of the object .bubbles . This object also provides additional properties that allow listeners to access information related to the propagation.

    • E.target refers to the event target.
    • E.currenttarget is the node on which the listener is registered. It is the same as the context value of the calling listener, which is this the value referenced by the keyword.
    • We can even know the current stage through E.eventphase. This is an integer representing three Event constructor constants CAPTURING_PHASE , BUBBLING_PHASE andAT_TARGET。


Put into practice

Let's put this concept into practice. In the following pen(translator Note: Refers to one of the Codepen), there are 5 nested boxes, respectively named b0 ... b4 . Initially, only the outer box b0 is visible, and the inner box is displayed when the mouse hovers over it. When we click on a box, the log of the propagation stream is displayed in the table on the right.

Look at the Pen Jmxdpz created by SitePoint (@SitePoint) on Codepen.

You can even click outside the box: In this case, the event target will be BODY or HTML element, depending on where the click on the screen stops propagating

Event propagation can be stopped by any listener by invoking the Stoppropagation method of the event object. This means that listeners registered on all nodes after the current target on the propagation path are not called. Instead, the listener for the current target registration will still receive an event notification.

We can check this behavior by using a simple example derived from the previous Demo, just insert the call to stoppropagation () in one of the listeners. Now we have added a new capture listener at the top of the Listener list registered to window:

 1   Window . AddEventListener (' click ', E + = {e.stoppropagation ();}, true< /span>);  2  true );  3  window . AddEventListener (' Click ', Listener (' C2 '), true );  4   5   6  

In this way, no matter which box is clicked, the propagation will end early, only to reach the window registered capture listener immediately stop propagating

Stopimmediatepropagation, as its name expresses, stops propagation directly, preventing the peer listener of the current listener from receiving events. We can see this from a small change to the previous Pen:

 1   Window . AddEventListener (' click ', E + = {e.stopimmediatepropagation ();},  2  true );  3  window . AddEventListener (' Click ', Listener (' C2 '), true );  4   5   6  

Now there's nothing to output to the log table, either from the c1 trap or the c2 trap, because propagation stops after the new listener is executed. Event cancellation

Some events are associated with the default action that the browser performs at the end of propagation. For example, clicking a link element or clicking the form submit button causes the browser to navigate to the new page, or submit the form separately.

You can avoid performing this default behavior when an event is canceled, by calling the event object E.preventdefault in the listener to block the default behavior. Conclusion

In this way, I want to be able to show you how event bubbling and event capture work in JavaScript. If you have any questions or comments, I am happy to hear these questions and comments in the discussion below. Reference

    • Document Object Model (DOM) Level 2 Events specification
    • Dom4–events
    • Dom–living standard–events
    • UI events–dom Event Architecture
    • Msn–events and the DOM

Event bubbling in JavaScript? Explanation of event propagation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.