Dom Event bubbling and capturing

Source: Internet
Author: User

Original: Event order translation: hh54188 's Blog

Foreword: Although the mastery of jquery, but not very understanding of its prototype JavaScript, recently in learning JavaScript encountered some difficulties, such as bubble and capture, many times mentioned, but do not know where the application. Found some good Article FAQ, here to share with you.

Quirksmode a series of articles are good, easy to understand, this article is just a series of one, have the opportunity to translate the JavaScript series are translated to everyone.

The original address is here http://www.quirksmode.org/js/events_order.html, the sentence is marked "(. "I am not very understanding of this sentence, may be wrong." Official start:

The order in which events occur

The origin of this problem is very simple, assuming you have another element nested within one element

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

: And both have an OnClick event handler function (event handler). If the user clicks Element 2, the click events for element 1 and element 2 are triggered. But which event is triggered first. Which event handler function will be executed first. In other words, the order in which events occur.

Two kinds of models

Predictably, Netscape and Microsoft had two distinct ways of dealing with the "horrible" (Browser wars) days: Netscape argued that element 1 was the first occurrence, and that the sequence of events called capture Microsoft kept the element 2 priority, This sequence of events is called bubbling

These two sequence of events are diametrically opposed. The Explorer browser only supports bubbling events, both Mozilla,opera7 and Konqueror support. And the older opera and icab don't support either.

Capture Event

When you are using a Catch type event

               | |
---------------| |-----------------|
element1   | | | -----------| |-----------     |
|   | Element2  \/          |   | | -------------------------     |
|        Event Capturing          |
-----------------------------------

: The event handler function for element 1 is first triggered, and the event handler for element 2 is finally triggered

Bubbling Event

When you use a bubble type event

               /\
---------------| |-----------------|
element1   | | | -----------| |-----------     |
|   | Element2 | | | |   -------------------------     |
|        Event Bubbling           |
-----------------------------------

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

The model of the Consortium

The consortium wisely chose an option in the battle. Any event that occurs in the model of the event is first entered into the capture phase until the target element is reached and then into the bubbling phase

                 | |  /\
-----------------| |--| |-----------------|

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

For a web developer, you can choose whether to bind the event handler in the capture or bubbling phase, which is implemented through the AddEventListener () method, and if the last argument of this function is true, the function is bound to be captured in the capture phase, or false, Bind functions in the bubbling phase.

Suppose you want to do 1 2 3 element1.addeventlistener (' click ', Dosomething2,true) element2.addeventlistener (' Click ', DoSomething, False

If the user clicks Element 2, the following occurs:

(The event here is like a tourist, traveling from outside to inside, gradually approaching the main element that was triggered, and then moving backwards) Click the event to begin the capture phase (gradually approaching the direction of element 2). See if there is a DISCOVERY element 1 in the ancestor element 2 that has the onclick handler function in the capture phase, so the doSomething2 is checked to the target itself (element 2), and no more processing functions are found in the capture phase. The event begins to enter the bubbling phase, assuming the dosomething (), which is bound to the element 2 bubbling phase of the function. Event to move away from element 2 to see if any ancestor elements bind a handler function in the bubbling phase. There is no such situation, so nothing has happened

The opposite is: 1 2 3 Element1.addeventlistener (' click ', Dosomething2,false) element2.addeventlistener (' Click ', DoSomething, False

Now if the user clicks on element 2 It will happen: Click the event to enter the capture phase. To see if there is an onclick handler in the capture phase of the ancestor element 2, the result of the event is checked to the target itself. The event begins to enter the bubbling phase and performs a function bound to the element 2 bubbling phase. The DoSomething () event begins to move away from the target, checking that the ancestor element of element 2 has a discovery that binds the handler function in the bubbling phase, and that the doSomething2 () of element 1 is executed

Compatibility and traditional patterns

In browsers that support the Element1.onclick DOM (Document Object model), the traditional event binding method is 1 = doSomething2;

Default is considered to be binding in the bubbling phase

Using bubbling Events

Few developers are aware of the use of bubbling events or capture-type events. In the Web page they made today, there is no need for an event to be handled by several functions because of bubbling. But sometimes users are often confused because there are many situations after they have clicked only one mouse (multiple functions are executed because of bubbling). And in most cases you want your processing functions to be independent of each other. When a user clicks on an element, what happens, clicks on another element, and corresponds to what happens, independent of each other, not because of the bubbling chain.

It's been happening.

The first thing you need to understand is that event capture or bubbling is happening all the time.   If you give the entire page document a definition of a generic onclick handler function 1 2 3 4 5 Document.onclick = dosomething;   if (document.captureevents) document.captureevents (Event.click); I do not know what the meaning of the second sentence, beginners, I hope there are capable to explain

Clicking on any element on the page will eventually bubble to the top document layer of the page, thus triggering that generic handler unless the previous handler explicitly indicates that the bubble is terminated so that it does not propagate to the entire document level

Usage (this section translation is not good, because there is no actual combat, I am not very understanding, you can add in the message, I will update)

Because any event propagation terminates at the page document (this top-level), which makes the default event handler possible, suppose you have a page

------------------------------------
| document                         |
|   ---------------------------| | | element1 | |  element2   | | ---------------  ------------  |
|                                  |
------------------------------------
1 2 3 Element1.onclick = dosomething; Element2.onclick = dosomething; Document.onclick = defaultfunction;

Now if the user clicks Element 1 or Element 2,dosomething () will be executed. If you prefer, if you don't want to let the event bubble up to the execution defaultfunction (), you can stop the event bubbling up to propagate here. But if the user clicks on the other part of the page, Defaultfunction () will still be executed. This kind of effect may sometimes be used on.

Set the page--the processing function has a larger area of trigger, which is required in the drag-and-drop script. Generally speaking, the occurrence of a MouseDown event on an element layer means that the element is selected and enables it to respond to MouseMove events. Although MouseDown is usually bound to this element layer to avoid browser bugs, the other two event functions must be scoped to the entire page (. )

Remember that the first rule of browserology is that everything is possible (anything can happen) and is at least a little prepared. So what's likely to happen is that when users drag and drop, a significant move on the page of his mouse, the script is not in a large response, so that the mouse will no longer stay on the element layer if the onmouseover handler function is bound to the element layer, this element layer will not have any response to the mouse movement, This makes the user wonder if the onmouseup handler function is bound to the element layer, the event cannot be triggered, and the result is that the element layer continues to react to the mouse movement after the user wants to drop the element layer. This can cause (users) more confusion (. )

So in this case, event bubbling is very useful because putting your processing functions on the page layer guarantees that they will always be executed.

Turn it off.

But generally, you will want to turn off all bubbles and capture to ensure that the function does not disturb each other. In addition, if your document structure is quite complex (many of the table are nested or so on), you will also turn off bubbling to conserve system resources. At this point, the browser has to check each ancestor of the target element to see if it has a handler function. Even if one did not find it, just the search also took a lot of time

In the Microsoft model, you must set the Cancelbubble property of the event to true 1 Window.event.cancelBubble = True

You must invoke the Stoppropagation () method of the event in the model of the E.stoppropagation 1 ()

This prevents all bubbling from spreading outward.   This should be done as a cross-browser solution: 1 2 3 4 5 6 7 8 9 a function dosomething (e) {if (!e) var e = window.event;   E.cancelbubble =true;   if (e.stoppropagation) e.stoppropagation (); }

Setting cancelbubble in browsers that support cancelbubble properties is harmless. The browser will shrug and create this property. Of course this doesn't really cancel bubbles, but at least it guarantees that the command is safe and correct.

Currenttarget

As we've seen before, an event with target or srcelement attribute is used to indicate exactly which target element the event occurred on (that is, the element that the user initially clicked on). In our example is element 2, because we clicked it.

It is important to understand that the target element in the capture or bubbling phase is invariant and is always associated with element 2.

But suppose we bind the following function 1 2 3 Element1.onclick = dosomething; Element2.onclick = dosomething;

If the user clicks Element 2, dosomething () is executed two times. But how do you know which HTML element is responding to this event. Target/srcelement also gave no clues, but people were always more inclined to element 2 because it was the cause of the event (because the user clicked it).

To solve this problem, the Currenttarget attribute is added to the consortium, which points to the element that is handling the event: That's exactly what we need. Unfortunately, there is no similar attribute in the Microsoft model.

You can also use the "this" keyword. In the example above, it is equivalent to the HTML element in which the event is being processed, like Currenttarget.

Problems with the Microsoft model

But when you use the Microsoft event-binding model, the This keyword does not correspond to HTML elements. Lenovo lacks a Microsoft model similar to the Currenttarget attribute (. If you do this, you mean: 1 2 3 element1.attachevent (' onclick ', dosomething) element2.attachevent (' onclick ', dosomething)

You don't know exactly which HTML element is responsible for handling events, which is the most serious problem with the Microsoft event-binding model, which is why I never used it, even if I was developing an application for IE only under Windows.

I would like to be able to add currenttarget similar attributes as soon as possible--or follow the standards. This information is needed by web developers

Postscript:

Because there is no actual combat JavaScript, so this article some places I am not very understanding, can only be hard to translate out, such as talking about the effect of the drag, if you have any additional and questions you can leave a message to me, thank you support.


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.