Detailed Analysis of Event Bubbling Mechanism in JavaScript

Detailed Analysis of Event Bubbling Mechanism in JavaScript

What is bubbling?

There are three stages in DOM event flow: event capture stage, target stage, and event bubbling stage.

Event capturing: In simple terms, when the mouse clicks or a DOM event is triggered, the browser will propagate the event from the root node from the outside to the inside. That is, if a child element is clicked, if the parent element has registered the corresponding event through event capturing, the event bound to the parent element will be triggered first.

Event bubbling (dubbed bubbling): In contrast to event capture, event bubbling is an event propagation from the inside out to the root node.

The triggering order of the DOM standard event flow is: capture first and then bubbling. That is, when a DOM event is triggered, the event will be captured first, and then the event will be bubbled through event propagation after the event source is captured. Different browsers have different implementations for this. IE10 and below do not support capture events, so there is one less event capture stage. IE11, Chrome, Firefox, Safari and other browsers all have this feature.

addEventListener() Method

This method sets an event listener and performs actions with the specified parameters when a certain event occurs. The syntax is:

addEventListener(event, function, useCapture)

The parameter event is required and indicates the event to be monitored, such as click, touchstart, etc., which are the events without the prefix on.

The function parameter is also required, indicating the function to be called after the event is triggered. It can be an externally defined function or an anonymous function.

The parameter useCapture is optional. You can enter true or false to describe whether the event is bubbling or capturing. true means capturing, and the default false means bubbling.

Remove event listener

If you want to remove the event listener added by addEventListener(), you need to use removeEventListener(). The syntax is:

removeEventListener(event, function)

The parameters are the same as addEventListener().

compatibility

IE 8 and earlier, and Opera 7.0 and earlier, do not support the addEventListener() and removeEventListener() methods. They use the following methods instead:

Add an event:

attachEvent(event, function)

Remove event:

**detachEvent(event, function) **

Compatibility issues can be resolved in the following ways:

if (div1.addEventListener) {
         div1.addEventListener('click', function () {
             console.log("Support")
         });
} else if (div1.attachEvent) {
         div1.attachEvent('onclick', function () {
             console.log("Not supported")
         });
}

The specific difference between bubbling and capturing

HTML

    <div id="div1">
         <div id="div2"></div>
    </div>

JS

<script>
        var div1 = document.getElementById("div1");
        var div2 = document.getElementById("div2");
        div1.addEventListener('click',function(){
            console.log("div1--capture phase")
        },true);
        div2.addEventListener('click',function(){
            console.log("div2--capture phase")
        },true);
        div1.addEventListener('click',function(){
            console.log("div1--bubble stage")
        });
        div2.addEventListener('click',function(){
            console.log("div2--bubble stage")
        });
</script>

Output result (the result of execution when div2 is clicked)

Solution

function stopBubble(e) {
         if (e && e.stopPropagation) {
                e.stopPropagation(); //So it supports W3C's stopPropagation() method } else {
             window.event.cancelBubble = true; //Otherwise, we need to use IE's method to cancel event bubbling}
}

Summarize

This is the end of this article about the event bubbling mechanism in JavaScript. For more relevant JavaScript event bubbling content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A brief analysis of event bubbling and event capture in js
  • Introduction to event bubbling and event capture in JS
  • Detailed explanation of JS bubbling events and event capture examples
  • Detailed explanation of js event delegation
  • JavaScript adds event listeners to event delegation in batches. Detailed process
  • Detailed explanation of javascript event bubbling, event capture and event delegation

<<:  Examples of optimistic locking and pessimistic locking in MySQL

>>:  Summary of MySQL time statistics methods

Recommend

About front-end JavaScript ES6 details

Table of contents 1. Introduction 1.1 Babel Trans...

Detailed explanation of CSS image splicing technology (sprite image)

CSS image splicing technology 1. Image stitching ...

Introduction to container of() function in Linux kernel programming

Preface In Linux kernel programming, you will oft...

Solution to nacos not being able to connect to mysql

reason The mysql version that nacos's pom dep...

HTML Basics: HTML Content Details

Let's start with the body: When viewing a web ...

Detailed explanation of the principle of Docker image layering

Base image The base image has two meanings: Does ...

JavaScript function encapsulates random color verification code (complete code)

An n-digit verification code consisting of number...

Detailed explanation of MySQL InnoDB secondary index sorting example

Sorting Problem I recently read "45 Lectures...

How to use docker compose to build fastDFS file server

The previous article introduced a detailed exampl...

Solution to elementui's el-popover style modification not taking effect

When using element-ui, there is a commonly used c...

JS implements the dragging and placeholder functions of elements

This blog post is about a difficulty encountered ...

MySQL data types full analysis

Data Type: The basic rules that define what data ...

How to write CSS elegantly with react

Table of contents 1. Inline styles 2. Use import ...