JS event bubbling and event capture and its blocking details

Source: Internet
Author: User

Although proficient in jquery, but not very familiar with its prototype JavaScript, recently encountered some difficulties in learning JavaScript, such as bubbling and capturing, many times mentioned, but do not know exactly where to apply. Find some good articles for your doubts, and share them here.

I. Order of occurrence of events

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

Copy CodeThe code is as follows:
-----------------------------------
| 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, what is the order in which events occur?

Ii. Two models

Unsurprisingly, Netscape and Microsoft have two very different ways of dealing with the "terrible" (Browser wars) days:

Netscape asserts that element 1 events occur first, and this sequence of events is called the capture type
Microsoft retains the priority of element 2, a sequence of events called bubbling
The sequence of the two events is diametrically opposed. The Explorer browser only supports bubbling events, both Mozilla,opera7 and Konqueror support. And the older opera and Icab both don't support

Iii. Capture-type events

When you use capture-type events

Copy CodeThe code is as follows:
| |
---------------| |-----------------
|                element1 | | |
| -----------| |-----------     |
|     |element2 \/| |
| -------------------------     |
| Event Capturing |
-----------------------------------
: The event handler for element 1 is first triggered, and the event handler for element 2 is finally triggered

Four, Bubble type event

When you use bubbling events

Copy CodeThe code is as follows:
/ \
---------------| |-----------------
|                element1 | | |
| -----------| |-----------     |
|          |element2 | |     | |
| -------------------------     |
| Event Bubbling |
-----------------------------------
: The handler function for element 2 is first triggered, element 1 is followed by

Five, the model

The wisdom of the market has chosen a choice in this battle. Any event that occurs in the event model is the first to enter the capture phase until the target element is reached and then into the bubbling phase

Copy CodeThe code is as follows:
| | / \
-----------------| |--| |-----------------
|  element1 | |                | | |
| -------------| |--| |-----------     |
|          |element2 \/| |     | |
| --------------------------------     |
| Event Model |
------------------------------------------
For a web developer, you can choose to bind the event handler in the capture or bubbling phase, which is implemented by the AddEventListener () method, if the last parameter of the function is true, the function is bound in the capture phase, and vice versa, The function is bound during the bubbling phase.

Suppose you're going to do

Copy CodeThe code is as follows:
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, from outside to inside, gradually approaching the main element of the trigger, and then leaving in reverse)

1. Click the event to begin the capture phase first (gradually approaching the direction of element 2). View whether there is an onclick handler function in the ancestor element of element 2 in the capture phase
2. Found that element 1 has one, so doSomething2 is executed
3. The event is checked to the target itself (element 2), and no more processing functions are found in the capture phase. The event begins to go into the bubbling phase, assuming that dosomething (), a function bound to the bubbling phase of element 2, is taken for granted.
4. The event is directed away from element 2 to see if any ancestor elements are bound to a handler function during the bubbling phase. There was no such situation, so nothing happened.
The opposite is the case:

Copy CodeThe code is as follows:
Element1.addeventlistener (' click ', Dosomething2,false)

Element2.addeventlistener (' click ', Dosomething,false)


Now if the user clicks on element 2 it will happen:

1. Click events to enter the capture phase. See if there is an onclick handler function in the ancestor element of element 2 in the capture phase, resulting in nothing
2. The event is checked to the target itself. The event begins to enter the bubbling phase and performs functions that are bound to the bubbling phase of element 2. DoSomething ()
3. The event starts away from the target and checks whether the ancestor element of element 2 has a handler that is bound in the bubbling phase.
4. One was found, so the doSomething2 () of element 1 is executed

Vi. compatibility and traditional models

In browsers that support the Web-based DOM (Document Object model), the traditional event binding method is

Copy CodeThe code is as follows: Element1.onclick = doSomething2;
Default is considered to be bound to the bubbling phase

Vii. use of bubble-type events

Few developers are aware of the use of bubbling events or captured events. In the Web pages they make today, it is not necessary to let an event be handled by several functions because of bubbling. But sometimes users are often confused because there are a number of things that happen after they click the mouse only once (multiple functions are executed because of bubbling). In most cases, you want your processing functions to be independent of each other. When the 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.

Eight, has been happening

The first thing you should 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

Copy CodeThe code is as follows:
Document.onclick = dosomething;
if (document.captureevents) document.captureevents (Event.click);

Clicking on any element's click event on the page will eventually bubble up to the top document layer of the page, 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 plane


Add to the second sentence of the above code:

>>> first say IE
Object.setcapture () When an object is SetCapture, his method will be inherited to the entire document for capture.
When you do not need to inherit the method to the entire document capture, use Object.releasecapture ()
>>>others
Mozilla also has a similar function, the method is slightly different
Window.captureevents (Event.eventtype)
Window.releaseevents (Event.eventtype)
>>>example

Copy CodeThe code is as follows://If there is only the following sentence, then only click obj is triggered click Obj.onclick = function () {alert ("Something")}
If you add the following sentence, the method will be inherited to document (or window, different browser) to capture
Obj.captureevents (Event.click); Ff
Obj.setcapture ()//ie

Ix. usage

Because any event propagation terminates at the page document (the highest level), this makes the default event handler possible, assuming you have such a page

Copy CodeThe code is as follows:
------------------------------------
| Document |
| ---------------  ------------  |
| |  element1 | |  Element2 | |
| ---------------  ------------  |
| |
------------------------------------
Element1.onclick = dosomething;
Element2.onclick = dosomething;
Document.onclick = defaultfunction;

Now if the user clicks on element 1 or the element 2,dosomething () will be executed. If you wish, if you do not want the event to bubble up to the execution of defaultfunction (), you can stop the event bubbling up and propagate up here. However, if the user clicks on other parts of the page, Defaultfunction () will still be executed. Such effects may sometimes be used.

Setting the page-—— makes the processing function have a large range of trigger area, which is required in the "drag effect" script. In general, the occurrence of an MouseDown event on an element layer means that this element is selected and enables it 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 Browser science (browserology) is: Everything is possible (anything can happen), and at least when you are prepared. So it's possible that when a user drags a page and moves his mouse over a large screen, the script doesn't react so much that the mouse stops at the element level.

1. If the onmouseover handler is bound to the element layer, the element layer will no longer react to the mouse movement, which will make the user feel strange
2. If the onmouseup handler is bound to an element layer, the event cannot be triggered, as the result is that the element layer continues to respond to the mouse movement after the user wants to drop the element layer. This will cause (the user) more confusion (?). )

So in this case, event bubbling is very useful because putting your handler on the page layer ensures that they can be executed all the time.

Ten, turn it Off (Stop the event bubbling)

But in general, you'll want to turn off all the bubbles and captures to ensure that the functions don't disturb each other. In addition, if your document structure is quite complex (many table nesting or the like), you can 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 is not found, just the search also takes a lot of time

In Microsoft's model, you must set the Cancelbubble property of the event to True

Copy CodeThe code is as follows: Window.event.cancelBubble = True
You must invoke the Stoppropagation () method of the event in the model
Copy CodeThe code is as follows: E.stoppropagation ()
This will prevent all bubbling from spreading outward. And as a cross-browser solution, this should be the scenario:
Copy CodeThe code is as follows:
function DoSomething (e)

{
if (!e) var e = window.event;

E.cancelbubble = true;

if (e.stoppropagation) e.stoppropagation ();

}

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

Xi. Currenttarget

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

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

But suppose we bind the following function

Copy CodeThe code is as follows: Element1.onclick = dosomething;

Element2.onclick = dosomething;


If the user clicks on element 2, dosomething () is executed two times. But how do you know which HTML element is responding to this event? Target/srcelement also does not give clues, but people are always more inclined to element 2, because it is the cause of the event (because the user clicked on it).
To solve this problem, the Currenttarget this property, which points to the element that is handling the event: This is exactly what we need. Unfortunately, there are no similar attributes in the Microsoft model.
You can also use the "this" keyword. In the example above, it is equivalent to the HTML element that is processing the event, just like Currenttarget.

12. Problems with Microsoft Model

But when you use the Microsoft Event binding model, the This keyword is not the equivalent of an HTML element. Lenovo lacks a Microsoft model like the Currenttarget attribute (? )--by following the code above, you would mean:

Copy CodeThe code is as follows: 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 use it, even if I'm developing an app for Windows-only ie.

I want to be able to increase currenttarget similar properties as soon as possible--or follow the standard? Web developers need this information

JS event bubbling and event capture and its blocking details

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.