


Detailed 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
----------------------------------
| 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
| --- --------| |----------- |
| |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
| - ----------| |----------- |
| |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
--
| element1 | | | | |
| -------------| |--| |----------| |
| |element2 / | | |
| -------------------------------- |
| W3C event model |
---------------------------------------------
Suppose you want to do
element2.addEventListener('click',doSomething,false)
(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:
element2.addEventListener('click',doSomething,false)
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.
In browsers that support w3c dom (Document Object Model), the traditional event binding method is
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 timeThe 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
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
//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
------------------------------ --------
| 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
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
In the w3c model you must call the stopPropagation() method of the event
This will prevent all bubbling from propagating outward. As a cross-browser solution, this should be done:
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
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:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

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.

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:

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

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)

What are the commonly used commands to prevent bubbling events? In web development, we often encounter situations where we need to handle event bubbling. When an event is triggered on an element, such as a click event, its parent element will also trigger the same event. This behavior of event delivery is called event bubbling. Sometimes, we want to prevent an event from bubbling up, so that the event only fires on the current element, and prevents it from being passed to superior elements. To achieve this, we can use some common directives that prevent bubbling events. event.stopPropa
