Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the way for JavaScript to prevent events from bubbling?

Shulou Source: shulou.com Published: 2022-06-02 08:03:35 10月18日 Update

This article shows you what JavaScript prevents event bubbles. The content is concise and easy to understand. It will definitely make your eyes shine. I hope you can gain something through the detailed introduction of this article.

What we need to pay attention to is: the characteristics of the event bubble itself will bring disadvantages and benefits, which I will explain in detail in subsequent blogs.

So we're going to talk about how to stop events bubbling here.

For example, if we have a child box and a parent box, both child boxes and parent boxes have click events, but in this case, when we click on the child box, we only want the child box to display click events. Here we will use the method to prevent the event bubble to block the event display of the parent box.

Create two boxes and add click events to them, as follows:

Document .father{ margin: 100px auto; width: 100px; height:100px; overflow: hidden; background-color: palegreen; } .son{ width: 50px; height: 50px; margin-left: 25px; margin-top: 25px; background-color: paleturquoise; } var father = document.querySelector('.father'); var son = document.querySelector('.son'); son.addEventListener('click',function(){ alert('son'); },false) father.addEventListener('click',function(){ alert('father'); },false)

When we click on the click event of the child box, the printed result is:

How do we block click events on the parent box?

You can add stopPropagation() directly to the click event inside the child box,

As follows:

son.addEventListener('click',function(e){ alert('son'); e.stopPropagation(); },false)

At this point, the result of the operation is:

Interruption successful.

However, it should be noted that this method also has compatibility issues. In older browsers (IE 6-8), it is usually operated by using the cancelBubble property of the event object. That is, add directly to the corresponding click event:

e.cancelBubble = true;

If we want to solve this compatibility problem, we can use the following methods:

if(e && e.stopPropagation){ e.stopPropagation(); }else{ window.event.cancelBubble = true; } This is JavaScript's way to stop event bubbles. What do you know or know? If you want to learn more skills or enrich your knowledge reserves, please pay attention to the industry information channel.

Tags: Events boxes methods compatibility content skills knowledge results problems concise successful concise two size blog disadvantages advantages objects that is properties Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Redmi vpn NVidia Shulou Tech Info