Introduction to JavaScript event bubbling and application examples

Source: Internet
Author: User

I. What is event bubbling?

Trigger a certain type of event on an object (such as clicking an onclick event). If this object defines the event handler, this event will call this handler, if the event handler is not defined or the event returns true, the event will be propagated to the parent object of the object, from the inside out, until it is processed (all similar events of the parent object will be activated), or it reaches the top level of the object hierarchy, that is, the document Object (Some browsers are windows ).

For example, if you want to appeal a case in the local court, if the local court does not handle such cases, the local authorities will help you continue to appeal to the higher court, such as from the municipal level to the provincial level, to the Central Court, your case will be handled.

Ii. What is the function of event bubbling?

(1) event bubbling is allowedMultiple operations are processed in a centralized manner(Add the event processor to a parent element to avoid adding the event processor to multiple child elements .)Capture events at different levels of the object Layer.

[Centralized processing example]

Copy to ClipboardReference: [www.bkjia.com] <div onclick = "eventHandle (event)" id = "outSide" style = "width: 100px; height: 100px; background: #000; padding: 50px ">
<Div id = "inSide" style = "width: 100px; height: 100px; background: # CCC"> </div>
</Div>
<Script type = "text/javascript">
// In this example, the processing method is defined only in the outer box, and this method can capture the click behavior of the child element and process it. If there are thousands of sub-elements to be processed, should we add "onclick =" eventHandle (event) "for each element )""? Obviously there is no such centralized processing method, and its performance is also higher.
Function eventHandle (e)
{
Var e = e | window. event;
Var obj=e.tar get | e. srcElement;
Alert (obj. id + 'was click ')
}
</Script>

(2) LetDifferent objects capture the same event at the same timeAnd call your own exclusive processing program to do your own thing, just like the boss's command, their employees did their jobs.

[Capture the same event at the same time]

Copy to ClipboardReference: [www.bkjia.com] <div onclick = "outSideWork ()" id = "outSide" style = "width: 100px; height: 100px; background: #000; padding: 50px ">
<Div onclick = "inSideWork ()" id = "inSide" style = "width: 100px; height: 100px; background: # CCC"> </div>
</Div>
<Script type = "text/javascript">
Function outSideWork ()
{
Alert ('My name is outSide, I was working ...');
}

Function inSideWork ()
{
Alert ('My name is inSide, I was working ...');
}

// The following program automatically activates the click event, which is not allowed by Some browsers. Therefore, click the gray box and start the command from here. This is because of the bubble, the large black box also receives the Click Event and calls its own processing program. If more boxes are nested, the same principle is true.

/*
Function bossOrder ()
{
Document. getElmentById ('inside '). click ();
}
BossOrder ();
*/
</Script>

3. What should I pay attention?

● There are actually three methods to capture events. Event bubbling is only one of them: (1) IE from inside to outside (inside → outside. (2) Netscape4.0 capture events from the outside to the inside. (3) DOM event stream, first from outside to inside, then back to origin from inside to outside (outside → inside → outside) (it seems that the object will trigger two event processing. What is the role of this method? I don't understand it !).

● Not all events can bubble up. The following events do not bubble: blur, focus, load, and unload.

● Event capture methods are different in different browsers or even different versions of the same browser. For example, Netscape4.0 adopts the capture event solution, while most other browsers support the bubble event solution. In addition, DOM Event streams also support text node event bubbling.

● The target of event capture reaching the top layer is also different in different browsers or different browser versions. In IE6, HTML receives event bubbles. In addition, most browsers extend the bubble to the window object, that is ...... Body → en → window.

● Blocking bubbles does not block the default behavior of objects. For example, when the submit button is clicked, the form data will be submitted, which does not need to be customized.

4. Prevent event bubbles

In general, we are all in place to identify the origin of our events, and do not want the browser to help us find the appropriate event processing program, that is, we define the most accurate goal, in this case, event bubbling is not required. In addition, through the understanding of event bubbling, we know that the program will do more extra things, which will inevitably increase the program overhead. Another important issue is that event bubble processing may activate events we didn't want to activate, leading to program disorder and even failed debugging, this is often a tricky issue for programmers who are unfamiliar with event bubbling. So when necessary, we need to prevent event bubbles.

[Example of activation of events that do not want to be activated]

Copy to ClipboardReference: [www.bkjia.com] <div onclick = "openWin ('HTTP: // www.baidu.com ')" id = "outSide" style = "width: 100px; height: 100px; background: #000; padding: 50px ">
<Div onclick = "openWin ('HTTP: // www.google.com ')" id = "inSide" style = "width: 100px; height: 100px; background: # CCC "> </div>
</Div>

<Script type = "text/javascript">
// In this example, you actually want to click the gray box to open the google homepage, and click the black box to open the baidu homepage. However, when you click the gray box, two webpages are opened at the same time. In fact, this problem is rarely encountered in actual design. You may think that if I place different buttons or links in different DOM depths of the page, will event triggering at a deep layer affect buttons at the top layer? No, because buttons cannot form nested relationships.
Function openWin (url)
{
Window. open (url );
}
</Script> The following is a method I copied online. I put this method at the end of the precise target object processing program. After this event is triggered and processed, the event will not be bubbling.

[Example of blocking event bubbles]

Copy to ClipboardReference: [www.bkjia.com] <div onclick = "showMsg (this)" id = "outSide" style = "width: 100px; height: 100px; background: #000; padding: 50px ">
<Div onclick = "showMsg (this)" id = "inSide" style = "width: 100px; height: 100px; background: # CCC"> </div>
</Div>
<Script type = "text/javascript">
// After the event is blocked from bubbling, click the gray box. The dialog box is displayed only once (note that the dialog box is compared with the default situation)
Function showMsg (obj)
{
Alert (obj. id );
StopBubble (event)
}

// Stop the event bubble Function
Function stopBubble (e)
{
If (e & e. stopPropagation)
E. stopPropagation ()
Else
Window. event. cancelBubble = true
}
</Script>

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.