JavaScript event bubbling and capturing and bubbling advantages

Source: Internet
Author: User


Event flow refers to the order in which events are received in the page, IE, Firefox, and Chrome browsers are event bubbling, which is called event bubbling, where events are first received by the most specific elements and then propagated up to the nodes that are not specific. Event capture is the opposite, event capture was proposed by Netscape, event bubbling and capturing as shown in the following illustration:






While event capture is the only event flow model supported by Netscape, the current IE9, Firefox and Google also support this event flow model.




The benefits of event bubbling

Because events have a bubbling mechanism, we can use the principle of bubbling to add events to the parent and trigger the execution effect. The benefit of this is of course to improve performance.

If we could have a lot of li using a for loop, it would have a better effect on performance.
Here we can use the event delegate to achieve this effect.


<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
window.onload = function () {
var aUl = document.getElementsById("bubble");
var aLi = aUl.getElementsByTagName("li");
//In any event, as long as the element you operate on is the event source.
// ie:window.event.srcElement
//Under the standard: event.target
aUl.onmouseover = function (ev) {
var ev = ev || window.event;
var target = ev.target || ev.srcElement;
if(target.nodeName.toLowerCase() == "li"){
target.style.background = "blue";
}
}
aUl.onmouseout = function (ev) {
var ev = ev || window.event;
var target = ev.target || ev.srcElement;
if(target.nodeName.toLowerCase() = "li"){
target.style.background = "";
}
}
}
</script>
</head>
<body>
<div>
<ul id = "bubble">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
</body>










Stop bubbles




<div onclick="showMsg(this,event)" id="outSide" style="width:100px; height:100px; background:#000; padding:50px">
<div onclick="showMsg(this,event)" id="inSide" style="width:100px; height:100px; background:#CCC"></div>
</div>
<script type="text/javascript">
//After preventing the event from bubbling, you click on the gray box, and the dialog box will only pop up once in the whole process (note the comparison with the default situation)
function showMsg(obj,e)
{
alert(obj.id);
stopBubble(e)
}
//Prevent event bubbling function
function stopBubble(e)
{
if (e &amp;&amp; e.stopPropagation)
e.stopPropagation()
Else
window.event.cancelBubble=true
}
</script>






JS event bubble and event capture
(1) Bubble event: events are triggered in the order from the most specific event target to the least specific event target (document object).
IE 5.5: div -> body -> document
IE 6.0: div -> body -> html -> document
Mozilla 1.0: div -> body -> html -> document -> window
(2) Event capturing: events are triggered from the most imprecise object (document object) and then to the most precise (events can also be captured at the window level, but must be specified by the developer).
(3) DOM event flow: two event models are supported: capture event and bubble event, but capture event occurs first. Both event flows touch all objects in the DOM, starting with the document object and ending with the document object.
The most unique property of the DOM event model is that text nodes also trigger events (not in IE).
The W3C standard browsers use the addeventlistener (event, FN, usecapture) method when adding events. The third parameter in the base, usecapture, is a Boolean value, which is used to set whether events are executed when they are captured or when they are bubbling. The W3C incompatible browser (ie) uses attachevent() method, which has no relevant settings. However, the event model of IE is executed when the event bubbles by default, that is, when usecapture is equal to false, so it is safer to set usecapture to false when handling the event, which also realizes the effect of compatible browser.
Event bubbling and capturing of JavaScript and its advantages - event bubbling and event capturing
Event capture stage: the event is searched from the top level label until the event target is captured.
Event bubble phase: the event starts from the event target and bubbles up to the top level tag of the page.
Let's say that an element div has a subordinate element P.
<div>
<p>Elements</p>
</div>
These two elements are bound with the click event. If the user clicks P, it triggers the click event on div and P. which of these two event handlers executes first? What is the sequence of events?
Two models
Before, Netscape and Microsoft were different implementations.
In Netscape, div is triggered first, which is called event capture.
In Microsoft, P triggers first, which is called event bubbling.
The two events are handled in exactly the opposite order. Ie only supports event bubbling. Mozilla, Opera 7 and Konqueror are all supported. The older versions of opera's and icab are not.
Event capture
When you use event capture, the parent element is triggered first, the child element is triggered later, that is, div is triggered first, P is triggered later.
Event Bubbling
When you use event bubbling, the child element is triggered first, the parent element is triggered later, that is, P is triggered first, div is triggered later.
W3C model
The W3C model is to neutralize the two. In the W3C model, when any event occurs, event capture starts from the top level until the event trigger reaches the event source element. Then, the event bubbles up from the event source until it reaches the document.
Programmers can choose whether to use event capture or event bubble when binding events. The method is to use the addeventlistener function when binding events. It has three parameters. If the third parameter is true, it means to use event capture. If it is false, it means to use event bubble.
ele.addEventListener('click',doSomething2,true)
True= capture
False= bubbles
Traditional binding event mode
In a browser that supports W3C DOM, event bubbling is the way to bind events like this.
ele.onclick = doSomething2
IE browser
As mentioned above, ie only supports event bubbling, does not support event capture, nor does it support the addeventlistener function. It does not use the third parameter to indicate whether it is bubbling or capturing. It provides another function, attachevent.
ele.attachEvent("onclick", doSomething2);
Appendix: event bubbling (process): the event starts from the occurrence target (event. Srcelement|event. Target) and bubbles up the document layer by layer until the document.
The propagation of events can be prevented:
• in W3C, use the stoppropagation () method
• set cancelbubble = true under ie;
In the process of capture, stoppropagation(); after that, the subsequent bubbling process will not occur~
3. Block the default behavior of the event, such as jump after click < a >~
• in W3C, use the preventdefault() method;
Set window.event.returnvalue = false under ie;
4. Wow, it's finally finished. Not all events can bubble while testing the amount written, such as blur, focus, load and unload.

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.