Table of Contents
Concept
Example
Event bubbling example 2
Event Capture Example 2
Event bubbling and capturing examples
Event Delegate Example 2
Home Web Front-end JS Tutorial Event capture, event bubbling and event delegation mechanism in Javascript

Event capture, event bubbling and event delegation mechanism in Javascript

Mar 01, 2017 pm 03:17 PM

Concept

Event bubbling: The deepest element triggered by the event receives the event first. Then its parent element, and so on, until the document object finally receives the event. Although the document has no independent visual representation from the html element, it is still the parent element of the html element and events can bubble up to the document element.
Let’s talk about event capture casually.
Event capture: The event first occurs in the highest-level object (document) of the DOM tree and then propagates to the deepest element. (Note that IE6 only has bubbling, not capturing)
Event delegation: I think event delegation uses the bubbling principle to convert event monitoring to its parent element, that is, bind the event to the parent element, and then Get the child element object in the event and perform corresponding operations on it. Advantages: 1. Improve performance 2. Reduce the amount of code

Example

Event bubbling example 1

Events are executed in the bubbling stage by default
First look at the following code :

<script type="text/javascript">
    window.onload=function(){
        var oId1=document.getElementById(&#39;id1&#39;);        
        var oId2=document.getElementById(&#39;id2&#39;);        
        var oId3=document.getElementById(&#39;id3&#39;); 

        oId1.addEventListener(&#39;click&#39;,function(e){
            console.log("点击了id1");
        });

        oId2.addEventListener(&#39;click&#39;,function(e){
            console.log("点击了id2");

        });

        oId3.addEventListener(&#39;click&#39;,function(e){
            console.log("点击了id3");
        });
    }</script><style type="text/css">
    *{margin: 0;padding: 0;}</style>
    <p id="box" style="background-color:#669;widht:600px; height:400px;">
    <p id="id1" style="background-color:#F00;widht:500px;height:300px;">
    <p id="id2" style="background-color:#6F9;widht:400px; height:200px;">
        <p id="id3" style="background-color:#000;widht:300px; height:100px;">
        </p>
    </p></p></p>
Copy after login

I clicked id1, id2, and id3 in sequence, and the execution effect is as follows:
Event capture, event bubbling and event delegation mechanism in Javascript
Analysis: Because when clicking id3, bubbling starts from id3 first, and binding on id3 is performed. The event bubbles to id2, executes the event above id2, and finally executes the event above id1.

Event bubbling example 2

Now start to prevent the bubbling of id2, modify the JS as follows

window.onload=function(){
        var oId1=document.getElementById(&#39;id1&#39;);        
        var oId2=document.getElementById(&#39;id2&#39;);        
        var oId3=document.getElementById(&#39;id3&#39;); 

        oId1.addEventListener(&#39;click&#39;,function(e){
            console.log("点击了id1");
        });

        oId2.addEventListener(&#39;click&#39;,function(e){
            console.log("点击了id2");
            e.stopPropagation();

        });

        oId3.addEventListener(&#39;click&#39;,function(e){
            console.log("点击了id3");
        });
    }

</script>
Copy after login

At this time, I click on id1, id2, and id3 in sequence, and the execution effect is as follows Figure:
Event capture, event bubbling and event delegation mechanism in Javascript
Because the event is executed to id2 and no longer bubbles, when clicking id2 or id3, the event bound to id1 will not be executed.

Event Capture Example 1

In order to verify that the event is executed during the capture phase, I changed the JS code to the following:

<script type="text/javascript">
    window.onload=function(){
        var oId1=document.getElementById(&#39;id1&#39;);        
        var oId2=document.getElementById(&#39;id2&#39;);        
        var oId3=document.getElementById(&#39;id3&#39;); 

        oId1.addEventListener(&#39;click&#39;,function(e){
            console.log("点击了id1");
        },true);

        oId2.addEventListener(&#39;click&#39;,function(e){
            console.log("点击了id2");

        },true);

        oId3.addEventListener(&#39;click&#39;,function(e){
            console.log("点击了id3");
        },true);
    }</script>
Copy after login

At this time, I clicked on id1, id2, and id3 in sequence , the execution effect is as shown below:
Event capture, event bubbling and event delegation mechanism in Javascript
Analysis: Every time you click, the event will be executed starting from the root element, that is, it will be captured. If there is an event, it will be executed.

Event Capture Example 2

At this time, I changed the JS code to the following:

<script type="text/javascript">
    window.onload=function(){
        var oId1=document.getElementById(&#39;id1&#39;);        
        var oId2=document.getElementById(&#39;id2&#39;);        
        var oId3=document.getElementById(&#39;id3&#39;); 

        oId1.addEventListener(&#39;click&#39;,function(e){
            console.log("点击了id1");
        },true);

        oId2.addEventListener(&#39;click&#39;,function(e){
            e.stopPropagation();
            console.log("点击了id2");

        },true);

        oId3.addEventListener(&#39;click&#39;,function(e){

            console.log("点击了id3");
        },true);
    }</script>
Copy after login

At this time, I clicked on id1, id2, and id3 in sequence, and the execution effect is as follows :
Event capture, event bubbling and event delegation mechanism in Javascript
I discovered a phenomenon. When I clicked on id3, I found that the events bound to id1 and id2 were executed. Why not execute the event on id3? It turns out that canceling bubbling e.stopPropagation(); also prevents event capture.

Event bubbling and capturing examples

Now I modify the JS as follows:

<script type="text/javascript">
    window.onload=function(){
        var oId1=document.getElementById(&#39;id1&#39;);        
        var oId2=document.getElementById(&#39;id2&#39;);        
        var oId3=document.getElementById(&#39;id3&#39;); 


        oId1.onclick=function(){  //该事件在冒泡阶段执行
            console.log("点击了id1");
        }

        oId2.addEventListener(&#39;click&#39;,function(e){
            console.log("点击了id2");

        },true);

        oId3.addEventListener(&#39;click&#39;,function(e){

            console.log("点击了id3");
        },true);
    }</script>
Copy after login

At this time, I click on id1, id2, and id3 in sequence, and the execution effect is as follows:
Event capture, event bubbling and event delegation mechanism in Javascript

Event Delegate Example 1

The following code, when I bind the click event to the box, I can get which element was clicked through e.srcElement.

<script type="text/javascript">
    window.onload=function(){
        var oBox=document.getElementById(&#39;box&#39;);
        oBox.onclick=function(e){
            var curObj=e.srcElement;
            console.log(curObj.id);
        }
    }</script><style type="text/css">
    *{margin: 0;padding: 0;}</style>
    <p id="box" style="background-color:#669;widht:600px; height:400px;">
    <p id="id1" style="background-color:#F00;widht:500px;height:300px;">
    <p id="id2" style="background-color:#6F9;widht:400px; height:200px;">
        <p id="id3" style="background-color:#000;widht:300px; height:100px;">
        </p>
    </p></p></p>
Copy after login

Event capture, event bubbling and event delegation mechanism in Javascript
It can be seen that we can get the clicked element in the box binding click event.

Event Delegate Example 2

Verify bubbling in the event delegate
Change the above JS to the following:

<script type="text/javascript">
    window.onload=function(){
        var oBox=document.getElementById(&#39;box&#39;);        
        var oId2=document.getElementById(&#39;id2&#39;);

        oId2.onclick=function(e){
            e.stopPropagation();
        }
        oBox.onclick=function(e){
            var curObj=e.srcElement;
            console.log(curObj.id);
        }
    }</script>
Copy after login

Click at this time and you will find that id2, id3 , it cannot be obtained through e.srcElement. Because I stopped the bubbling of id2.

Event capture, event bubbling and event delegation mechanism in Javascript

The above is the content of event capture, event bubbling and event delegation mechanism in Javascript. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Understand the event bubbling mechanism: Why does a click on a child element affect the event of the parent element? Understand the event bubbling mechanism: Why does a click on a child element affect the event of the parent element? Jan 13, 2024 pm 02:55 PM

Understanding event bubbling: Why does a click on a child element trigger an event on the parent element? Event bubbling means that in a nested element structure, when a child element triggers an event, the event will be passed to the parent element layer by layer like bubbling, until the outermost parent element. This mechanism allows events on child elements to be propagated throughout the element tree and trigger all related elements in turn. To better understand event bubbling, let's look at a specific example code. HTML code: <divid="parent&q

Why does event bubbling trigger twice? Why does event bubbling trigger twice? Feb 22, 2024 am 09:06 AM

Why does event bubbling trigger twice? Event bubbling (Event Bubbling) means that in the DOM, when an element triggers an event (such as a click event), the event will bubble up from the element to the parent element until it bubbles to the top-level document object. . Event bubbling is part of the DOM event model, which allows developers to bind event listeners to parent elements, so that when child elements trigger events, the events can be captured and processed through the bubbling mechanism. However, sometimes developers encounter events that bubble up and trigger twice.

Reasons and solutions for jQuery .val() failure Reasons and solutions for jQuery .val() failure Feb 20, 2024 am 09:06 AM

Title: Reasons and solutions for the failure of jQuery.val() In front-end development, jQuery is often used to operate DOM elements. The .val() method is widely used to obtain and set the value of form elements. However, sometimes we encounter situations where the .val() method fails, resulting in the inability to correctly obtain or set the value of the form element. This article will explore the causes of .val() failure, provide corresponding solutions, and attach specific code examples. 1.Cause analysis.val() method

Why can't click events in js be executed repeatedly? Why can't click events in js be executed repeatedly? May 07, 2024 pm 06:36 PM

Click events in JavaScript cannot be executed repeatedly because of the event bubbling mechanism. To solve this problem, you can take the following measures: Use event capture: Specify an event listener to fire before the event bubbles up. Handing over events: Use event.stopPropagation() to stop event bubbling. Use a timer: trigger the event listener again after some time.

What scenarios can event modifiers in vue be used for? What scenarios can event modifiers in vue be used for? May 09, 2024 pm 02:33 PM

Vue.js event modifiers are used to add specific behaviors, including: preventing default behavior (.prevent) stopping event bubbling (.stop) one-time event (.once) capturing event (.capture) passive event listening (.passive) Adaptive modifier (.self)Key modifier (.key)

Why does the event bubbling mechanism trigger twice? Why does the event bubbling mechanism trigger twice? Feb 25, 2024 am 09:24 AM

Why does event bubbling happen twice in a row? Event bubbling is an important concept in web development. It means that when an event is triggered in a nested HTML element, the event will bubble up from the innermost element to the outermost element. This process can sometimes cause confusion. One common problem is that event bubbling occurs twice in a row. In order to better understand why event bubbling occurs twice in a row, let's first look at a code example:

Which JS events don't bubble up? Which JS events don't bubble up? Feb 19, 2024 pm 09:56 PM

What are the situations in JS events that will not bubble up? Event bubbling (Event Bubbling) means that after an event is triggered on an element, the event will be transmitted upward along the DOM tree starting from the innermost element to the outermost element. This method of transmission is called event bubbling. However, not all events can bubble up. There are some special cases where events will not bubble up. This article will introduce the situations in JavaScript where events will not bubble up. 1. Use stopPropagati

What is event bubbling? In-depth analysis of event bubbling mechanism What is event bubbling? In-depth analysis of event bubbling mechanism Feb 20, 2024 pm 05:27 PM

What is event bubbling? In-depth analysis of the event bubbling mechanism Event bubbling is an important concept in web development, which defines the way events are delivered on the page. When an event on an element is triggered, the event will be transmitted starting from the innermost element and passed outwards until it is passed to the outermost element. This delivery method is like bubbles bubbling in water, so it is called event bubbling. In this article, we will analyze the event bubbling mechanism in depth. The principle of event bubbling can be understood through a simple example. Suppose we have an H

See all articles