On the event bubbling and event capture of JS

Source: Internet
Author: User

What is an event?

Events are specific moments of interaction that occur in a document and in a browser window. The event is the heart of the JavaScript app beating, and the glue that sticks everything together, and when we interact with the Web page in the browser for some type of interaction, the event occurs.

An event might be a user clicking on something, a mouse passing through a particular element, or pressing some key on the keyboard, something that might happen in a Web browser, such as when a Web page is loaded, or when a user scrolls or changes the window size.

What is the event flow:

The event flow describes the order in which events are accepted from the page, but interestingly, the Microsoft (IE) and Netscape (Netscape) development team has proposed two diametrically opposed event flow concepts,IE's event flow is the event bubbling stream (bubbling), The event stream of the Netscape is the event capture stream (capturing).

The first type: event bubbling

The event stream proposed by IE is called event bubbling, that is, when the event starts with the most specific element, and then propagates up to the less specific node , take a look at the following example:

<! DOCTYPE html>

Next we click on the P element on the page to see what happens:

As we said above, it will be received from one of the most specific elements, then spread upward, p=>button=>div=>body ... Event bubbling can be figuratively likened to putting a stone into the water, and bubbles will come up from the bottom.

The second type: Event Capture

The event stream proposed by Netscape is called an event capture stream.

The idea of the event capture stream is that less specific DOM nodes should receive the event earlier, and the most specific node should receive the event at the end, and for the same example above, click on the button, Then the click event Propagates as follows: (We'll use the third parameter of AddEventListener to simulate the event capture stream)

<! DOCTYPE html>varOp=document.queryselector (' P '); varOb=document.queryselector (' button '); varOd=document.queryselector (' div '); varObody=document.queryselector (' body '); Op.addeventlistener (' Click ',function() {Console.log (' P tag is clicked ')    },true); Ob.addeventlistener (' Click ',function() {Console.log ("Button is clicked")    },true); Od.addeventlistener (' Click ',function() {Console.log (' Div is clicked ')    },true); Obody.addeventlistener (' Click ',function() {Console.log (' Body is clicked ')    },true);</script></body>

Let's also look at the print results in the background:

As we can see, the most specific element receives events from the least specific element, contrary to the bubbling flow body=>div=>button=>p

Dom Event Flow:

The event flow defined by the ' DOM2 level event ' contains 3 stages, an event capture phase, a target stage, and an event bubbling phase . The first occurrence of an event captures the opportunity to intercept an event, then the actual target receives the event, and the last phase is the event bubbling phase, which can respond to the event at this stage.

In the DOM event stream, the target of the event does not receive events during the capture phase, which means that the event is stopped from document to <p> in the capture phase, the next phase is in the target phase, and the event occurs on <p> and is considered part of the bubbling phase in event handling , then, the bubbling phase occurs, and the event is propagated back to the document.

Here's an example of how we simulate it:

<! DOCTYPE html>varBtn=document.getelementbyid ("BTN"); Btn.onclick=function(event) {Console.log ("Div in target phase");}; Document.body.addEventListener ("Click",function(event) {Console.log ("Event Bubble Events bubbling");},false);d Ocument.body.addEventListener ("Click",function(event) {Console.log ("Event Catch Events capture");},true);</script></body>

See what the background gives you:

It is a process that captures, then processes, and then bubbles out.

About DOM Level 2 event handlers:

DOM Level 2 Events define two methods: actions to handle adding and deleting events: Add event addeventlistener () Delete event RemoveEventListener ()

Both methods are included in all DOM nodes, and they all contain 3 parameters : (1) The event mode to be handled (for example: Click,mouseover,dbclick ...). ) (2) The event handler function can be either an anonymous function or a named function (but if the event needs to be deleted, it must be a named function) (3) A Boolean value that represents whether it is in the event bubbling phase of processing or the event capture phase (true: indicates that the event handler is called during the capture phase; false: Indicates that the event handler is called during the bubbling phase)

The main benefit of using DOM Level 2 event handlers is that you can add multiple event handlers, which are triggered in their order, and events added via AddEventListener can only be removed with RemoveEventListener. The parameters passed in when removing must be the same as the parameters used when adding , which also means that the added anonymous function cannot be removed ( Note: Our default third parameter is false by default, which is added in the bubbling phase, and in most cases, the event handler is added to the bubbling phase of the event. This allows for maximum compatibility with each browser )

// This is the simplest way to add an event to a DOM Level 2 event (an anonymous function is added at this point)<! DOCTYPE html>var btn= Document.queryselector (' button ');        Btn.addeventlistener (' click ',function() {            console.log (' I am button ')        },  false)   // when the third argument is not written, the default is False (add event when bubbling)    </script></ Body>

So let's try to name the function:

<! DOCTYPE html>var btn= Document.queryselector (' button ');        Btn.addeventlistener (' click ', foo,false);         function foo () {            console.log (' I am a button'        )           }// actually the operation is to get the function that is written in it outside, Instead of </script></body>    

Then we add two events to try:

<! DOCTYPE html>varBtn=document.queryselector (' button '); //First EventBtn.addeventlistener (' Click ', foo,false); functionfoo () {Console.log (' I'm the button ')        }        //a second eventBtn.addeventlistener (' Click ', Newfoo,false); functionNewfoo () {Console.log (' I'm the New button ')        }    </script></body>

So let's see if there's any execution in the background, how the order is executed:

So, we add two events that are possible, and the order of events is executed in the order in which our program is written.

Let's try DOM level 0 event handlers.

<! DOCTYPE html>function foo () {            Console.log (2)        }        function  newfoo () {            Console.log ( 9)        }    </script></body>

Look at the results:

Only the first event is executed and the second is ignored, which is not the result we want, and Addeventliener will execute all two events.

End:

That's all the content of event bubbling, event capture, Dom event flow, Dom2 level event flow, thank you for reading

On the event bubbling and event capture of JS

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.