Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to Bubble and capture events in JS

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about how to bubble and capture events in JS. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

When I first came into contact with JS, I didn't know anything. I just thought about how to use the functions of Google and Baidu to solve practical problems. I wouldn't think of going to find out.

Gradually, with the deepening of the language of JS, there is an opportunity to understand some fundamental things. Recently, I have been watching the JQuery source code and have a lot of feelings. I always want to use the native JS to achieve one of my JQuery libraries. To tell you the truth, many functions and ideas in JQuery are the long-term contributions of thousands of open source workers, which can be digested in a short time.

Recently I ran into the addEventListener function again (the introduction to addEventListener on MDN is very detailed). Because I didn't understand the meaning of the third parameter before, I either set it to the default value or manually set it to false. This time, I read a lot of articles and thoroughly understood the bubbling and capture of the incident.

What event bubbles and captures

Event bubbling and capture are two ways of event propagation in DOM. For example, for two DOM elements that register the same event (simply two div, one inside and one outside), when you click on the inner div, who executes the two events first.

Bubbling event, from the inside out, the innermost element is executed first, and then bubbles to the outer layer.

Capture events, from the outside to the inside, the outermost element is executed first, and then passed to the inside.

Before IE 9, only event bubbling was supported, but both after IE 9 (including IE 9) and current mainstream browsers support both events.

How to set it, you only need to modify the third parameter of addEventListener. True is captured, false is bubbling, and the default is bubbling.

Give me a simple example.

Var dom_out = document.getElementsByClassName ('out') [0]; var dom_in = document.getElementsByClassName (' in') [0]; dom_out.addEventListener ('click',function () {alert (' out');}, false); dom_in.addEventListener ('click',function () {alert (' in');}, false)

In the above example, events are executed according to bubbles. Click on the in in the inner layer, and you will see that the order of alert is "in" and then "out". If you change the event to capture, the order of alert is different.

Var dom_out = document.getElementsByClassName ('out') [0]; var dom_in = document.getElementsByClassName (' in') [0]; dom_out.addEventListener ('click',function () {alert (' out');}, true); dom_in.addEventListener ('click',function () {alert (' in');}, true)

The above example is an example of capturing an event. Is the effect of clicking in different?

The reason for bubbling and capturing events (for example, pre-IE 9 browsers don't support capturing events, which is really anti-programmer), after all, in practice, there must be a sequence of things, either from the inside out or from the outside in, both are necessary.

But sometimes, in order to be compatible with browsers below IE 9, the third parameter is set to false or default (the default is false).

Learn more about bubbling and capture

Now that bubbling and capture have been made clear, what happens if bubbling and capture occur at the same time?

The original browser processing time is divided into two stages, the capture phase and the bubbling phase.

Execute the capture phase first, and if the event is executed during the capture phase (in the case of true), execute

Then there is the bubbling phase, which executes if the event is executed during the bubbling phase (in the case of false)

Let's take a look at the example:

S1 s2 s3

This time, we set three span, S1, S2, S3, and then set S1 span S3 to bubble execution and S2 to capture execution:

Var S1 = document.getElementsByClassName ('s1') [0]; var S2 = document.getElementsByClassName (' s2') [0]; var S2 = document.getElementsByClassName ('s3') [0]; s1.addEventListener (' click',function () {alert ('s1');}, false); s2.addEventListener (' click',function () {alert ('s2');}, true); s3.addEventListener (' click',function () {alert ('s3') }, false)

From the point of view of the running effect, click S3, alert S2 = > S3 = > S1, indicating:

Both the capture event and the bubbling event exist at the same time, and the capture event is executed first, and the bubbling event is executed later.

If there is an event in the element and the execution time of the event is the same as the current logic (bubbling or capture), it executes.

Default event cancels and stops bubbling

Of course, sometimes we just want to execute the innermost or outermost events and cancel a wider range of events according to the relationship between the inner and outer layers (for beginners, it's easy to get hit without canceling bubbles). Event.stopPropagation () (window.event.cancelBubble = true in IE) can be used to cancel event bubbling.

Sometimes the default event for the browser needs to be canceled, and the function used in this case is event.preventDefault () (window.event.returnValue = false in IE).

So what's the difference between canceling the default event and stopping bubbling? My understanding: the default event of the browser refers to the browser's own events (this is not nonsense), such as the click of the a tag, the submission of the form, etc., canceled will not be executed; bubbling is cancelled from the outside in (capture), from the inside out (bubbling), after stop, will not continue to traverse. Answers on stackoverflow

Take a look at the example, it is still the above example, but each function is added to stop bubbling:

S1.addEventListener ('click',function (e) {e.stopPropagation (); alert (' s1');}, false); s2.addEventListener ('click',function (e) {e.stopPropagation (); alert (' s2');}, true); s3.addEventListener ('click',function (e) {e.stopPropagation (); alert (' s3');}, false)

The result of the click is: when you click S2 or S3, you will alert S2, click S1 and pop up S1. Because the event is canceled, click S3 and execute S2, then it will not be executed downwards.

Let's look at an example of preventDefault.

Click me to go back to the home page var back = document.getElementsByClassName ('back') [0]; back.addEventListener (' click', function (e) {e.preventDefault ();})

The second link can not go back to the home page, because the browser's default event has been cancelled.

To sum up, add two IE-compatible functions:

Function stopBubble (e) {/ / if an event object is provided, this is a non-IE browser if (e & e.stopPropagation) / / so it supports the W3C stopPropagation () method e.stopPropagation (); else / / otherwise, we need to use IE to cancel the event bubbling window.event.cancelBubble = true } / / prevent the default behavior of the browser function stopDefault (e) {/ / block the default browser action (W3C) if (e & & e.preventDefault) e.preventDefault (); / / the way to block the default action of the function in IE else window.event.returnValue = false; return false } above is how the editor shares with you how to bubble and capture events in JS. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report