


JavaScript Event Learning Chapter 8 Sequence of Events_javascript skills
The basic question is simple. Suppose you have one element contained within another element.
------------ -----------------------
| 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
------------------| |------------------
| element1 | | |
| --------- --| |----------- |
| |element2 / | |
| ------- ------------------ |
| Event CAPTURING |
--------------------- ----------------
The event handler of element1 will be executed first, followed by element2.
Event bubbling
But when you use event bubbling
/
---------------| |------------------
| 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.
| | /
------ -----------| |--| |------------------
| 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:
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:
---- --------------------------------
| 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:
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

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

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.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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