JS event flow mechanism bubbling and capturing

Source: Internet
Author: User

The interaction between JavaScript and HTML is implemented through events. Event is a specific interaction moment that occurs in a document or browser window.

Event Flow

The order in which events are received from the page is called the event stream.

IE--Event bubbling stream

Netscape---event capture Stream

View Source: DOM2 Event-capture-bubbling

Event bubbling

The event stream of IE is called event bubbling, where the event starts with the most specific element (the node that is the deepest nesting level in the document) and then propagates up to the less specific node (document).

Let's start with a simple example, which is the HTML structure

<!DOCTYPE html>

has a DIV element. If we click on the <div> element, then what is the order of this click event?

We add listening events to several elements,

Element.addeventlistener (event, function, Usecapture)
Parameter description:

  • The event string. Specify the event name, such as Click, MouseEnter, MouseLeave
  • function functions. Specifies the function to execute when the event is triggered.
  • The Usecaption boolean value. Specifies whether the event is executed during the capture or bubbling phase. The default value is False, which means that the event is executed during the bubbling phase. True to execute during the capture phase
var div = document.getElementById('div')var body = document.bodyvar html = document.documentElementdiv.addEventListener('click', function () {  console.log('div标签')}, false)body.addEventListener('click', function () {  console.log('body ')},  false)html.addEventListener('click', function () {  console.log('html')},  false)document.addEventListener('click', function () {  console.log('document')}, false)

Then click on <div> the element to view the console output,

As can be seen from the above output, this click event is propagated in the following order:
<div>---> <body> ---> --->document

That is, the Click event occurs first in the target element, and then the click event propagates up the DOM tree to the Document object. This is the event bubbling.

Event bubbling is supported by all modern browsers. IE9, Firefox, Chrome, and Safari keep the event bubbling to the Window object.

If we set listener events on each DOM element, the order in which events are propagated is:
<div>---> <body> ---> ---> document --->window

Event capture

Another stream of events presented by the Netscape Communicator team is called event capture (capturing). Event captures are less specific nodes that should receive an event earlier, and the most specific node should receive the event last. Event capture is intended to capture an event before it reaches its intended destination.

We can still look at just the example, DOM structure unchanged, we modify the listener event

var div = document.getElementById('div')var body = document.bodyvar html = document.documentElementdiv.addEventListener('click', function () {  console.log('div标签')}, true)body.addEventListener('click', function () {  console.log('body ')},  true)html.addEventListener('click', function () {  console.log('html')},  true)document.addEventListener('click', function () {  console.log('document')}, true)

Then, click on the <div> element to get the result

As you can see from the example above, the event goes: document ---> ---> <body> ---><div>

That is, during the event capture process, the document object receives the Click event First, and then the event goes down in the DOM tree and continues to propagate to the actual target of the event, the <div> element. This is the event capture. And the event bubbling process, diametrically opposite.

Although the DOM2 level event specification requires events to propagate from the document object, most modern browsers start capturing events from the Window object.
If we set listener events on each DOM element, the order in which events are propagated is:
window---> document ---> ---> <body> ---><div>

Because it is not supported in older browsers, there are fewer event captures, unless they are used for special needs.

Dom Event Flow

The event flow defined by the "DOM2 level event" consists of three phases: the event capture phase, the target stage, and the event bubbling phase.

The first occurrence is event capture, which provides an opportunity to intercept the event. Then the actual target receives the event. The final stage is the bubbling phase, in which events can be responded to at this stage.

??

    • Event capture phase: In the DOM event stream, the actual target ( <div> element) does not receive events during the capture phase. This means that during the capture phase, events are stopped from document to back <body> .

    • In the target phase: Events <div> occur on top and are considered part of the bubbling phase in event handling.

    • Event bubbling phase: The bubbling phase occurs, and the event propagates back to the document.

Although the DOM2 level event specification explicitly requires that the capture phase does not involve event targets, modern browsers IE9 and above trigger events on the event target object during the capture phase. As a result, there are two opportunities to manipulate events above the target object, that is, step 4 in, which can occur during the capture phase or during the bubbling phase.

The DOM event stream is not supported in earlier versions of IE8, and modern browsers support DOM event streams.

Application of Event Flow

The typical application for event flow comparison is event delegation. Event delegation takes advantage of event bubbling, specifying only one event handler to manage all events of a type.

Let's look at a common example, which is the DOM structure of an unordered list:

  <ul>    <li id="li1">我是第1个li</li>    <li id="li2">我是第2个li</li>    <li id="li3">我是第3个li</li>  </ul>

Our need is to click on different columns to output different messages.

    • The first approach: to <li> Add a click event to each, so that the event can be handled separately, showing different content.
document.getElementById('li1').addEventListener('click', function(e) {    console.log('我是第一个li')}, false)document.getElementById('li2').addEventListener('click', function(e) {    console.log('我是第2个li')}, false)document.getElementById('li3').addEventListener('click', function(e) {    console.log('我是第3个li')}, false)

Clicking on each one <li> will output the corresponding content.

    • The second approach: <li> <ul> Add a processing event to the element's parent element,
document.querySelector('ul').addEventListener('click', function (e) {  console.log(e.target.innerText)}, false)

Clicking on each one <li> will show the contents of the different <li> Chinese text elements.

In this code, we only <ul> add an onclick event handler for the element. Because all <li> are <ul> child nodes of the element and their events are bubbling, the Click event will eventually be processed by this function.

These two ways, the second has the advantage:

    1. Lower upfront consumption. Because only one DOM element was obtained, only one event handler was added.

    2. Consumes less memory. Each function is an object and consumes memory.

    3. Better performance. The more objects in memory, the worse the performance.

    4. If you want to add or subtract elements later, and you <li> don't have to modify the event method, you can get the same result.

Therefore, the second way of comparison is recommended.

Events that are best suited to use event delegation techniques include,,,, click mousedown mouseup keydown , keyup and keypress . Although mouseover and mouseout events also bubble, it is not easy to handle them properly, and it is often necessary to calculate the position of the elements.

Resources:

JavaScript Advanced Programming (Third Edition)-Chapter 13th events

View Source: DOM2 Event-capture-bubbling

JS event flow mechanism bubbling and capturing

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.