search
HomeWeb Front-endJS TutorialJavaScript Event Learning Chapter 8 Sequence of Events_javascript skills

The basic question is simple. Suppose you have one element contained within another element.

Copy code The code is as follows:

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

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

These two Elements all have onclick event handlers. If the user clicks on element2 then the click event is triggered on both element 2 and element 1. But which event happened first? Which event handler will be executed first? In other words, what is the event order?

Two modes
There is no doubt that both Netscape and Microsoft made their own decisions during the bad days in the past.
Netscape said element1 happened first. This is called event capturing.
Microsoft thinks element2 happened first. This is called event bubbling.
The order of these two events is exactly the opposite. IE only supports event bubbling. Mozilla, Opera 7 and Konqueror support both. Earlier Opear and iCab browsers do not support either.

Event Capture
When you use event capture
Copy the code The code is as follows:


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

The event handler of element1 will be executed first, followed by element2.

Event bubbling
But when you use event bubbling
Copy the code The code is as follows:

/
---------------| |------------------
| element1 | | |
| ---------- -| |----------- |
| |element2 | | | |
| --- ----------------------- |
| Event BUBBLING |
----------------- ------------------

The event handler of element2 will be executed first, and the event handler of element1 will be executed later.

W3C Mode
W3C decided to maintain gravity in this war. In the W3C event model, any event that occurs is first captured until it reaches the target element, and then bubbles up.
Copy code The code is as follows:

| | /
------ -----------| |--| |------------------
| element1 | | | | |
| -- --------- --| |--| |----------- |
| |element2 / | | | |
| ------ -------------------------- |
| W3C event model |
------------ -------------------------------

As a designer, you can choose to register the event handler in the capturing or bubbling stage. This can be accomplished through the addEventListener() method introduced in the advanced mode before. If the last parameter is true, it is set to event capturing, if it is false, it is set to event bubbling.

Suppose you write like this
element1.addEventListener('click',doSomething2,true)
element2.addEventListener('click',doSomething,false)
If the user clicks on element2 The following things will happen:
, click event occurs in the capture phase. It seems that if any parent element of element2 has an onclick event handler, it will be executed.
, the event finds doSomething2() on element1, then it will be executed.
, the event is passed down to the target itself, and there is no other capture phase program. The event enters the bubbling phase and then doSomething() is executed, which is the event handler registered by element2 in the bubbling phase.
, the event is passed upwards and then checked to see if any parent element has set an event handler in the bubbling phase. There isn't one here, so nothing happens.
In reverse:
element1.addEventListener('click',doSomething2,false)
element2.addEventListener('click',doSomething,false)

Now if the user clicks on element2 What happens:
, event click occurs in the capture phase. The event will check whether the parent element of element2 has an event handler registered during the capture phase, which is not the case here.
, the event is passed down to the target itself. Then the bubbling phase starts and dosomething() is executed. This is the event handler registered in the bubbling phase of element2.
, the event continues to pass upward and then checks whether any parent element has registered an event handler during the bubbling phase.
, the event found element1. Then doSomething2() was executed.

Compatibility in legacy mode
For browsers that support the W3C DOM, legacy event registration

element1.onclick = doSomething2;
is considered Registered in the bubbling stage.

The use of event bubbling
Few designers are aware of event capturing or bubbling. In today's world of web page creation, there seems to be no need for a bubbling event to be handled by a series of event handlers. Users can also be confused by a series of events that occur after a click, and generally you want to keep your event handler code somewhat independent. When the user clicks on one element, something happens, and when he clicks on another element, then something else happens.
Of course this may change in the future, it is best to keep the model forward compatible. But the most practical event capture and bubbling today is the registration of default functions.

It will always happen
The first thing you need to understand is that event capturing or bubbling is always happening. If you define an onclick event for your entire page:
Copy the code The code is as follows:

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

Your click time on any element will bubble up to the page and then set off this event handler. Only if the preceding event handler explicitly prevents bubbling, it will not be passed to the entire page.

Use
Since each event will be stopped on the entire document, the default event handler becomes possible. Suppose you have a page like this:
Copy the code The code is as follows:

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

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

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

Now if the user clicks element1 or element2 then doSomething() will be executed. Here you can also stop his spread if you wish. If not, then defaultFunction() will be executed. The user's clicks elsewhere will also cause defaultFunction() to be executed. Sometimes this can be useful.
Setting a global event handler is necessary when writing drag code. Usually the mousedow event on a layer will select this layer and respond to the mousemove event. Although mousedown is usually registered at this level to avoid some browser bugs, other event handlers must be document-wide.
Remember the first law of browser logic: anything happens, often when you least prepare. What may happen is that the user's mouse moves wildly and the code does not keep up, causing the mouse to no longer be on this layer.
If an onmousemove event handler is registered on a layer, it will definitely confuse the user if the layer no longer responds to mouse movements.
If an onmouseup event handler is registered on a certain page, the program will not capture the layer when the user releases the mouse, causing the layer to still move with the mouse.
Event bubbling is important in this case because the global event handler is guaranteed to execute.

Turn it off
But usually you want to turn off all related capturing and bubbling. In addition, if your document structure is very complex (such as a lot of complex tables), you also need to turn off bubbling to save system resources. Otherwise, the browser has to check the parent element one by one to see if there is an event handler. Although there may not be one, searching is still a waste of time.
In Microsoft mode you must set the cancelBubble property of the event to true.
window.event.cancelBubble = true
In W3C mode you must call the stopPropagation() method.

e.stopPropagation()
This will stop the bubbling phase of this event. It is basically impossible to prevent the capture extreme of the event. I also want to know why.
A complete cross-browser code is as follows:
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 will be no problem if you set it in a browser that does not support cancelBubble. The browser will create such an attribute. Of course it's useless, just for safety.

currentTarget
As we said before, an event contains target or srcElement contains a reference to the element where the event occurred. In our case it is element2 because the user clicked on it.
It is important to understand that this target does not change during capture and bubbling: it always points to element2.
But suppose we register the following event handler:

element1.onclick = doSomething;
element2.onclick = doSomething;
If the user clicks element2 then doSomething() is executed twice. So how do you know which HTML element handles this event? target/scrElement cannot give the answer, it has been pointing to element2 from the beginning of the event.
In order to solve this problem, W3C added the currentTarget attribute. It contains a reference to the HTML element of the event being handled: the one we want. Unfortunately Microsoft mode does not have similar properties.
You can also use this keyword. In this example, it points to the HTML element of the event being processed, starting with currentTarget.

Problems with Microsoft model
But when you use Microsoft's event registration model, the this keyword does not only apply to HTML elements. Then there is no property like currentTarget, which means if you do:

element1.attachEvent('onclick',doSomething)
element2.attachEvent('onclick',doSomething)
You won't know which HTML element is handling the event. This is the most serious problem with Microsoft's event registration model, so don't use it at all, even for programs that only work under IE/win.
I hope Microsoft will add a property like currentTarget soon or follow the standard? We are in urgent need of design.

Continue
If you want to continue learning, please read the next chapter.
Original address: http://www.quirksmode.org/js/events_order.html
My twitter: @rehawk
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use