JavaScript Event Learning the sequence of events in the eighth chapter _javascript tips

Source: Internet
Author: User
The basic question is simple. Suppose one of your elements is contained in another element.
Copy Code code as follows:

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

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

Both of these elements have the OnClick event handler. If the user clicks on the Element2, then the click event is triggered on element 2 and element 1. But which incident happened first? Which event handler will execute first? In other words, what is the sequence of events (event order)?

Two types of models
There is no doubt that Netscape and Microsoft have made their own decisions in the last bad days.
Netscape said Element1 happened first. This is called event capture (capturing).
Microsoft felt that Element2 first happened. This is called event bubbling (bubbling).
The two sequences of events are just the opposite. IE only supports event bubbling. Mozilla,opera 7 and Konqueror are supported by two species. Earlier opear and icab browsers are not supported by two.

Event capture
When you use the event capture
Copy Code code as follows:


---------------| |-----------------
| element1 | | |
| --------- --| |----------- |
| |element2 \/| |
| ------------------------- |
| Event Capturing |
-----------------------------------

The Element1 event handler executes first, element2 after execution.

Event bubbling
But when you use event bubbling,
Copy Code code as follows:

/ \
---------------| |-----------------
| element1 | | |
| ---------- -| |----------- |
| |element2 | | |
| ------------------------- |
| Event Bubbling |
-----------------------------------

Element2 event handlers Execute first, element1 event handlers.

The mode of the consortium
The consortium decided to keep gravity in the war. Any event that occurs in the event model is captured first until the target element is reached and then bubbled.
Copy Code code as follows:

| | / \
-----------------| |--| |-----------------
| element1 | | | |
| ----------- --| |--| |----------- |
| |element2/| | |
| -------------------------------- |
| The event model of the Consortium |
------------------------------------------

As a designer, you can optionally register the event handler in the capture or bubbling phase. You can do this by using the AddEventListener () method described in the previous advanced mode. If the last argument is true, it is set to be event capture and, if False, is set to event bubbling.

Suppose you write this
Element1.addeventlistener (' click ', dosomething2,true)
Element2.addeventlistener (' click ', Dosomething,false)
If the user clicks on the Element2, the following event occurs:
, the Click event occurs during the capture phase. Thus, if any of the parent elements of the Element2 have an onclick event handler, it is executed.
, the event found DoSomething2 () on the element1, and then it is executed.
, the event is passed down until the target itself, and there is no other capture stage program. The event moves into the bubbling phase and then executes the dosomething (), which is the event handler that Element2 registers in the bubbling phase.
, the event is passed up, and the event handler is set by the parent element in the bubbling phase. There is nothing here, so nothing will happen.
Turn:
Element1.addeventlistener (' click ', Dosomething2,false)
Element2.addeventlistener (' click ', Dosomething,false)

Now, if the user clicks on the element2, it will happen:
, the event click occurs during the Capture phase. The event looks for the Element2 parent element to register the event handler in the capture phase, not here.
, the event is passed down until the target itself. Then start the bubbling phase, execute dosomething (), which is the event handler registered in the Element2 bubbling phase.
, the event continues to pass up and then checks whether a parent element registered an event handler in the bubbling phase.
, the incident found the element1. Then DoSomething2 () was executed.

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

Element1.onclick = doSomething2;
is considered to be registered in the bubbling phase.

Use of event bubbling
Few designers are aware of event capture or bubbling. In today's Web page, there seems to be no need to let a bubbling event be handled by a series of event handlers. Users will also be confused by a series of events after they click, and often you want to keep your event handler code Independent. When the user clicks on an element, something happens and when he clicks on other elements, then other things happen.
Of course in the future may change, it is best to make the mode forward compatible. But today's most useful event capture and bubbling is the registration of default functions.

It's always going to happen
The first thing you need to understand is that event capture or bubbling is always happening. If you define an onclick event for your entire page:
Copy Code code as follows:

Document.onclick = dosomething;
if (document.captureevents) document.captureevents (Event.click);

Your click time on any element will bubble to the page and start the event handler. The entire page is not delivered until the previous event handler explicitly blocks bubbling.

Use
Because each event will stop on the entire document, the default event handler becomes possible. Let's say you have a page like this:
Copy Code code as follows:

------------------------------------
| Document |
| --------------- ------------ |
| | element1 | | Element2 | |
| --------------- ------------ |

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

Element1.onclick = dosomething;
Element2.onclick = dosomething;
Document.onclick = defaultfunction;

Now if the user clicks on element1 or Element2 then DoSomething () will execute. Here, if you want, you can stop him from spreading. If not, then defaultfunction () will be executed. User clicks elsewhere will also allow Defaultfunction () to execute. Sometimes this can be useful.
Setting up a global event handler is necessary when you write the drag code. Usually a Mousedow event on one layer chooses this layer and then responds to the MouseMove event. Although MouseDown is usually registered on this layer to avoid some browser bugs, other event handlers must be global (document-wide).
Remember the first law of browser logic: Everything happens, and it's often when you're least prepared. What could happen is that the user's mouse is moving wildly and the code doesn't keep up, causing the mouse to no longer be on this layer.
If the OnMouseMove event handler is registered on a layer, it will surely confuse the user if the layer no longer responds to the mouse movement.
If a onmouseup event handler has been registered, the program does not capture when the user releases the mouse, causing the layer to move with the mouse.
In this case, event bubbling is important because the global event handler guarantees execution.

Turn it off
But usually you want to turn off all the relevant capture and bubbling. In addition, if your document structure is very complex (such as a large pile of complex tables) you also need to turn off bubbling to save system resources. Otherwise, the browser will have to see whether the parent element has an event handler. Although there may not be one, searching is a waste of time.
In Microsoft mode you have to say the cancelbubble property of the event is set to true.
Window.event.cancelBubble = True
You must call the Stoppropagation () method in the mode of the.

E.stoppropagation ()
This will prevent the bubbling phase of this event. Blocking the capture of an event is basically impossible. I also want to know why.
A complete cross-browser code is as follows:
Copy Code code as follows:

function DoSomething (e)
{
if (!e) var e = window.event;
E.cancelbubble = true;
if (e.stoppropagation) e.stoppropagation ();
}

Setting in browsers that do not support cancelbubble is not a problem. The browser creates one of these properties. Of course it's no use, just for safety.

Currenttarget
As we have said before, an event contains a reference to target or srcelement that contains an element that occurs in an event. In our example is Element2, because the user clicked on him.
It is important to understand that target does not change during capture and bubbling: He always points to element2.
But suppose we sign up for the following event handler:

Element1.onclick = dosomething;
Element2.onclick = dosomething;
If the user clicks Element2 then dosomething () executes two times. So how do you know that HTML element handles this event? Target/screlement can not give the answer, from the beginning of the event has been pointing to Element2.
To solve this problem, the Currenttarget attribute was added to the consortium. It contains a reference to the HTML element of the event being processed: the one we want. Unfortunately, the Microsoft model does not have a similar attribute.
You can also use the This keyword. In this example, the HTML element that points to the event being processed is currenttarget first.

The problem with the Microsoft model
But when you use the Microsoft Event Registration model, the This keyword is not just about HTML elements. And then there's not a property like Currenttarget, which means that if you do:

Element1.attachevent (' onclick ', dosomething)
Element2.attachevent (' onclick ', dosomething)
You don't know that HTML element is processing an event. This is the most serious problem with Microsoft's event registration model, so don't use it at all, even if it's just a ie/win program.
I hope Microsoft can add a similar currenttarget attribute or follow the standard as soon as possible? We are in urgent need of design.

Go on
If you want to continue to study, please read the next chapter.
Original address: http://www.quirksmode.org/js/events_order.html
My Twitter: @rehawk
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.