search
HomeWeb Front-endJS TutorialDetailed explanation of javascript event bubbling and methods of capturing and blocking_javascript skills

1. The sequence of events

The origin of this problem is very simple, suppose you have an element nested within another element

Copy code Code As follows:

----------------------------------
| element1                                                                                      | ------------------ |

--------------------- -----------

: And both have an onClick event handler. If the user clicks on element 2, the click events of both element 1 and element 2 will be triggered. But which event is triggered first? Which event handler function will be executed first? In other words, what was the exact sequence of events?

2. Two models

As expected, Netscape and Microsoft had two very different approaches to dealing with those days of the "browser wars":

Netscape advocates that the event of element 1 occurs first. This order of event occurrence is called the capturing type.

Microsoft maintains that element 2 has priority. This order of events is called the bubbling type.

Both of them The sequence of events is diametrically opposed. Explorer browser only supports bubbling events, Mozilla, Opera7 and Konqueror support both. The older opera and iCab do not support either



3. Capture events

When you use capturing events


---------------| |------------------
| element1 | | |
| --- --------| |----------- |
| |element2 / |
| --------------- ---------- |
| Event CAPTURING |
----------------------------- ------

: The event handler of element 1 is triggered first, and the event handler of element 2 is triggered last

4. Bubbling events

When you use bubbling events


Copy the code The code is as follows:                
---------------| |------------------
| element1 | | |
| - ----------| |----------- |
| |element2 | | |
| ---------- ------------- |
| Event BUBBLING |
-------------------------- ---------

: The processing function of element 2 is triggered first, followed by element 1

5. W3C Model

W3c wisely chose the right solution in this battle. Any event that occurs in the w3c event model first enters the capture phase until it reaches the target element, and then enters the bubbling phase


Copy code The code is as follows:

                                                               --
| element1 | | | | |
| -------------| |--| |----------| |
| |element2 / | | |
| -------------------------------- |
| W3C event model |
---------------------------------------------
As a web developer, you can choose whether to bind the event processing function in the capture phase or the bubbling phase. This is achieved through the addEventListener() method. If the last parameter of this function is true, then in the capture phase Phase binding function, otherwise false, binds the function in the bubbling phase.
Suppose you want to do


Copy code The code is as follows:
element1.addEventListener(' click',doSomething2,true)
element2.addEventListener('click',doSomething,false)

If the user clicks on element 2, what happens next:

(The event is like a tourist here, traveling from outside to inside, gradually approaching the main element that was triggered, and then leaving in the opposite direction)

1. The click event first enters the capture phase (gradually approaching the direction of element 2). Check whether any of the ancestor elements of element 2 has an onclick handler in the capture phase

2. It is found that element 1 has one, so doSomething2 is executed
3. The event checks the target itself (element 2), but there is no onclick handler in the capture phase Found more processing functions. The event begins to enter the bubbling stage, and doSomething() is executed naturally, which is a function bound to the bubbling stage of element 2.
4. The event moves away from element 2 to see if any ancestor element has a handler bound to it during the bubbling phase. There is no such case, so nothing happens
The opposite case is:

Copy the codeThe code is as follows:
element1.addEventListener('click',doSomething2,false)
element2.addEventListener('click',doSomething,false)

Now if the user clicks on element 2 it will happen:
1. Click the event to enter the capture phase. Check whether any of the ancestor elements of element 2 has an onclick handler in the capture phase, and find nothing

2. The event detects the target itself. The event begins to enter the bubbling phase, and the function bound to the bubbling phase of element 2 is executed. doSomething()
3. The event starts to move away from the target. Check whether any of the ancestor elements of element 2 has a handler function bound to it during the bubbling phase. 4. One is found, so doSomething2() of element 1 is executed.

6. Compatibility and traditional mode

In browsers that support w3c dom (Document Object Model), the traditional event binding method is


Copy code The code is as follows: element1.onclick = doSomething2;
is considered to be bound to the bubbling stage by default

7. Use bubbling events

Few developers will consciously use bubbling events or capturing events. In the web pages they make today, there is no need for an event to be handled by several functions because it bubbles up. But sometimes users are often confused because after they clicked the mouse only once many things happen (multiple functions are executed because of bubbling). In most cases you still want your processing functions to be independent of each other. When the user clicks on an element, what happens, and what happens when the user clicks on another element, are independent of each other and not linked by bubbling.

8. It happens all the time

The first thing you need to understand is that event capturing or bubbling is always happening. If you define a general onclick processing function for the entire page document


document.onclick = doSomething;
if (document.captureEvents) document.captureEvents(Event.CLICK);

The click event of clicking any element on the page will eventually bubble up to the highest document layer of the page, thus triggering the general processing function, unless the previous processing function explicitly points out that the bubbling is terminated. Will not be propagated to the entire document level


Addition to the second sentence of the above code:

>>> Let’s talk about IE first
object.setCapture() When an object is setCapture, its method will be inherited to the entire document for capture.
When you do not need to inherit the method to capture the entire document, use object.releaseCapture()
>>>others
Mozilla also has a similar function, the method is slightly different
window.captureEvents (Event.eventType)
window.releaseEvents(Event.eventType)
>>>example

Copy code The code is as follows:
//If there is only the following sentence, then click will be triggered only when obj is clicked obj.onclick = function(){alert("something")}
//If Add the following sentence, the method will be inherited to the document (or window, different browsers are different) to capture
obj.captureEvents(Event.click); //FF
obj.setCapture() // IE

9. Usage

Because any event propagation terminates in the page document (this top level), this makes the default event handler possible, assuming you have a page like this

Copy Code The code is as follows:

------------------------------ --------
| document                                                                   | element1 | | element2 | |
| --------------- ------------ |

----- ----------------------------------
element1.onclick = doSomething;
element2.onclick = doSomething;
document.onclick = defaultFunction;


Now if the user clicks on element 1 or element 2, doSomething() will be executed. If you wish, you can prevent events from bubbling up here if you don't want them to bubble up to defaultFunction(). But if the user clicks elsewhere on the page, defaultFunction() will still be executed. This effect may be useful sometimes.

Settings page - enables the processing function to have a larger trigger area, which is necessary in the "drag effect" script. Generally speaking, the occurrence of a mousedown event on an element layer means that the element is selected and enabled to respond to the mousemove event. Although mousedown is usually bound to this element layer to avoid browser bugs, the scope of the event functions of the other two must be the entire page (?)

Remember the First Law of Browserology: anything can happen, and that’s when you are at least somewhat prepared. So what may happen is that when the user drags and drags, he moves his mouse greatly on the page, but the script cannot respond to the large amplitude, so that the mouse no longer stays on the element layer

1. If the onmouseover handler function is bound to the element layer, this element layer will no longer respond to mouse movement, which will make users feel strange

2. If the onmouseup handler function is bound to the element layer , the event cannot be triggered. The consequence is that after the user wants to drop this element layer, the element layer continues to respond to mouse movement. This will cause more confusion (?)


So in this example, event bubbling is very useful, because placing your handler functions at the page level ensures that they can always be executed

10. Turn it off (to prevent events from bubbling)

But generally, you will want to turn off all bubbling and capturing to ensure that functions do not disturb each other. In addition, if your document structure is quite complex (many tables nested within each other, etc.), you may want to turn off bubbling to save system resources. At this point the browser has to check every ancestor of the target element to see if it has a handler function. Even if no one is found, the search just now still takes a lot of time

In the Microsoft model, you must set the cancelBubble property of the event to true


Copy the code The code is as follows:window.event.cancelBubble = true

In the w3c model you must call the stopPropagation() method of the event
Copy the code The code is as follows:
e.stopPropagation()

This will prevent all bubbling from propagating outward. As a cross-browser solution, this should be done:
Copy the code The code is as follows:

function doSomething(e)

{
  if (!e) var e = window.event;

e.cancelBubble = true;

if (e.stopPropagation) e.stopPropagation();

}

There is no harm in setting cancelBubble in browsers that support the cancelBubble attribute. The browser will shrug and create this attribute. Of course, this doesn’t really cancel bubbling, but it at least ensures that this command is safe and correct

11. currentTarget

As we saw before, an event uses the target or srcElement attribute to indicate which target element the event occurred on (that is, the element the user initially clicked on). In our case it's element 2 because we clicked on it.

It is very important to understand that the target element during the capture or bubbling phase does not change, it is always associated with element 2.

But suppose we bind the following function

Copy code The code is as follows:
element1.onclick = doSomething;

element2.onclick = doSomething;


If the user clicks element 2, doSomething() will be executed twice. But how do you know which html element is responding to this event? target/srcElement also gives no clue, but people will always prefer element 2 because it is the cause of the event (because it is what the user clicked on).
To solve this problem, w3c added the currentTarget attribute, which points to the element that is handling the event: this is exactly what we need. Unfortunately there is no similar attribute in Microsoft models
You can also use the "this" keyword. In the above example, it is equivalent to the html element that is handling the event, like currentTarget.

12. Problems with Microsoft model

But when you use the Microsoft event binding model, the this keyword is not equivalent to the HTML element. Lenovo lacks a Microsoft model similar to the currentTarget property (?) - if you follow the above code, you will mean:

Copy code The code is as follows:
element1.attachEvent('onclick',doSomething)

element2.attachEvent('onclick',doSomething)


You can’t know exactly which HTML element is responsible for handling the event. This is the most serious problem with Microsoft’s event binding model. To me, this This is also the reason why I never use it, even when developing applications only for IE under Windows

I hope to be able to add currentTarget-like properties soon - or follow the standard? Web developers need this information

Postscript:

Because I have never used JavaScript in practice, there are some parts of this article that I don’t quite understand, so I can only translate them abruptly, such as the section about the drag effect. If you have any additions or questions, you can leave a message to me. Thank you for your support!

Statement
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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.