Table of Contents
What is an event?
What is event flow:
DOM event flow
DOM level 2 event handler
Home Web Front-end JS Tutorial [JavaScript] Two completely opposite event flows: event bubbling and event capturing

[JavaScript] Two completely opposite event flows: event bubbling and event capturing

Aug 02, 2018 am 09:13 AM

What is an event?

Events are specific moments of interaction that occur between a document and a browser window.

What is event flow:

Event flow describes the order in which events are received from the page, but interestingly, Microsoft (IE) and Netscape (Netscape) ) The development team actually proposed two completely opposite event stream concepts. IE's event stream is event bubbling stream (event bubbling), while Netscape's event stream is event capturing stream (event capturing).

The first type: event bubbling

The event flow proposed by IE is called event bubbling, that is, the event starts with the most specific element Receive, and then propagate up to less specific nodes step by step

p——>body——>html——>document

Second type: event capture

Less specific nodes should receive events earlier, and the most specific nodes should receive events last. The purpose of capture is to capture an event before it reaches its intended destination.

document——>html——>body——>p

DOM event flow

"DOM2 level event" specified The event flow includes three stages: event capture stage, target stage, event bubbling stage

In the DOM event flow, the actual target will not receive events during the capture phase, which means that during the capture phase, The event stops after it reaches the body. The next stage is in the target stage, so the event occurs on p and is considered part of the bubbling stage in event processing. Then, the bubbling phase occurs and the event is propagated back to the document.

Even though the "DOM2-level events" specification clearly requires that the capture phase does not involve the event target, current mainstream browsers will trigger events on the event object during the capture phase. The result is that there are two opportunities to manipulate events on the target object.

DOM level 2 event handler

DOM level 2 events define two methods: operations for processing add events and deletion events:

Add event addEventListener() Delete event removeEventListener()

All DOM nodes contain these two methods, and they both contain 3 parameters: (1) The event method to be processed (for example : click, mouseover, dbclick...) (2) The event processing function can be an anonymous function or a named function (but if you need to delete the event, it must be a named function) (3) A Boolean value, representing Is it in the event bubbling stage processing or event capturing stage (true: means calling the event handler in the capturing stage; false: means calling the event handler in the bubbling stage)

//这是一个DOM 2级事件 添加事件最简单的方式(此时添加的是一个匿名函数)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <button>按钮</button>
    <script>
        var btn=document.querySelector(&#39;button&#39;);
        btn.addEventListener(&#39;click&#39;,function(){
            console.log(&#39;我是按钮&#39;)
        },false)   //当第三个参数不写时,也是默认为false(冒泡时添加事件)
    </script>

</body>
</html>
Copy after login
//添加的函数是命名函数,removeEventListener需要用这种方式
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <button>按钮</button>
    <script>
        var btn=document.querySelector(&#39;button&#39;);
        btn.addEventListener(&#39;click&#39;,foo,false);
        function foo(){
            console.log(&#39;我是按钮&#39;)
        }
           //其实操作就是把写在里面的函数拿到了外面,而在原来的位置用函数名来代替
    </script>
</body>
</html>
Copy after login

DOM2-level handler also supports adding two If an event handles an event, both events will be executed.

In most cases, we add the event handler to the bubbling phase of the event stream, so as to maximize compatibility. Various browsers.

It is best to only add event handlers to the capture phase when it is necessary to intercept the event before it reaches the target.

If it is not specifically needed, it is not recommended to register an event handler during the event capture phase.

Prevent event bubbling

It is mainly used to prevent event propagation. Prevents it from being dispatched to other DOM nodes and can be used at any stage of event propagation. The usage method is as follows (compatible with IE):

function stopBubble(event){
	if(window.event){
        //兼容IE
		window.event.cancelBubble=true;
	}else{
		event.stopPropagation();
	}
}
Copy after login

Block default events

function stopDefaultEvent(event){
	if(window.event){
        //兼容IE
		window.event.returnValue=false;
	}else{
		event.preventDefault()
	}
	return false;
}
Copy after login
Related articles:

Detailed explanation of JS bubbling events and event capture examples

How to implement JavaSript event bubbling and event capturing

Related videos:

JS Abstract Class and Event Design Pattern Video Tutorial

The above is the detailed content of [JavaScript] Two completely opposite event flows: event bubbling and event capturing. For more information, please follow other related articles on the PHP Chinese website!

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 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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles