Analysis of JavaScript event bubbling Application Instances

Source: Internet
Author: User

However, in some large WEB interaction projects today, such as large WebGame projects, the influence of JavaScript event bubbling is worth noting. This article uses a simple example to explain the JavaScript event bubbling and precautions.

If you don't have any idea about JavaScript event bubbling, let's take a look at my previous blog "introduction and application of JavaScript event bubbling". This article is practical and does not elaborate on the basic knowledge of JavaScript event bubbling too much.

Before starting the article, let's take a look at the following requirement: The following HTML assumes that it describes a web game project package bar (people who have played online games should know what the package bar or item bar is) you can drag the package title bar to any position on the page, and click the "X" button on the right of the title bar to close the display of the package bar. By observing the HTML structure, you can find that the close button is actually A link and is used as A child element of the title bar H5. To drag an element, we want to register the mousedown event with the dragged handle element, and click or click the close button to close the package. Based on this requirement, we will soon get the following code.

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ptml xmlns = "http://www.w3.org/1999/xhtml"> <pead> <meta http-equiv =" content-Type "content =" text/html; charset = UTF-8 "/> <title> JavaScript event bubbling instance 1 </title> <style type =" text/css "> # box {width: 200px; height: 100px; border: 2px solid blue} # box h5 {margin: 0; padding: 2px 5px; font-size: 18px; text-align: right; background: blue; cursor: move }# box h5 a {text-decoration: none; color: # FFF} </style> </pead> <body> × </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
In the above example, you find that when you click the close button, the mousedown event in the title bar is also triggered. Obviously this is expected, because you know that this is exactly what JavaScript event bubbling is working. In fact, when you click the close button, do not execute the mousedown event registered with the title H5, so you think of blocking event bubbling, and then modify the code to the following:
Copy codeThe Code is as follows:
<Div id = "box">
<H5 onmousedown = "startDrag ();"> <a onclick = "closeBox (event);" href = "javascript: void (0 ); "> × </a> <Div id = "testInfo"> </div>
</Div>
<Script type = "text/javascript">
Function startDrag ()
{
Document. getElementById ('testinfo'). innerHTML + = 'startdrag <br/> ';
}
Function closeBox (e)
{
Document. getElementById ('testinfo'). innerHTML + = 'closebox <br/> ';
StopBubble (e );
}
// Stop the event bubble Function
Function stopBubble (e)
{
If (e & e. stopPropagation)
E. stopPropagation ();
Else
Window. event. cancelBubble = true;
}
</Script>

As a result, when you click the close button, the mousedown event registered with the title H5 is still executed. What is the problem? In fact, you may find that the H5 title is not the same as the event registered at link A. In the above Code, we call the method to block the event in the click Event registered at link, this only means that the "similar events" registered by the parent element will not be executed. This means that if the H5 title also registers the click event, the click event will not be executed, the mousedown command continues. Here, the mousedown execution does not occur because you click the title bar. It is because the mousedown event is generated when you click the click button, and the existence of the JavaScript event bubbling mechanism, the event is broadcast to the parent and captured by the H5 title mousedown registration method. For more information about this, see my other blog "When onmousedown, onmouseup, and onclick are applied to the same label node Element at the same time". Now, through analysis, you should know how to do it. To make minor changes to the above Code, you just need to change the click event of link A to the mousedown event with the same title as H5, you can achieve the desired effect.
Related Topics:
Now let's talk about how to easily prevent event bubbles when developing with jQuery. JQuery, as an excellent script framework, is naturally outstanding in event encapsulation and browser compatibility processing. For more information, see my other blog "use jQuery's $. event. fix function to unify browser event processing".
There are two methods to prevent event bubbling by using jQuery:
1. Use event. preventDefault () directly for event objects that have been compatible with jQuery. The example code is as follows:
Copy codeThe Code is as follows:
<Script type = "text/javascript" src = "http://img.jb51.net/jslib/jquery/jquery.js"> </script>
<Div id = "box">
<H5 onmousedown = "startDrag ();"> <a onmousedown = "closeBox (event);" href = "javascript: void (0 ); "> × </a> <Div id = "testInfo"> </div>
</Div>
<Script type = "text/javascript">
Function startDrag ()
{
Document. getElementById ('testinfo'). innerHTML + = 'startdrag <br/> ';
}
Function closeBox (e)
{
Document. getElementById ('testinfo'). innerHTML + = 'closebox <br/> ';
Var event = $. event. fix (e );
Event. stopPropagation ();
}
</Script>

2. return false in the function bound to jQuery, that is, return false. Note: It is useless to return false instead of using the jQuery binding method. The Code is as follows:
Copy codeThe Code is as follows:
<Script type = "text/javascript" src = "http://img.jb51.net/jslib/jquery/jquery.js"> </script>
<Div id = "box">
<H5 onmousedown = "startDrag ();"> <a href = "javascript: void (0);"> × </a> <Div id = "testInfo"> </div>
</Div>
<Script type = "text/javascript">
Function startDrag ()
{
Document. getElementById ('testinfo'). innerHTML + = 'startdrag <br/> ';
}
Function closeBox ()
{
Document. getElementById ('testinfo'). innerHTML + = 'closebox <br/> ';
Return false;
}
$ ('# Box A'). bind ('mousedown', closeBox );
</Script>

Finally, we also need to explain that the second method is used to prevent event bubbling and the browser's default behavior is also blocked, in the handle method of the source code of jQuery event processing (jQuery JavaScript Library v1.3.2 2700 rows of non-compressed code), we can see the following processing to event. preventDefault () is used to prevent default browser behavior.
Copy codeThe Code is as follows:
Handle: function (event)
{
// Other code ......
If (ret = false)
{
Event. preventDefault ();
Event. stopPropagation ();
}
// Other code ......
}

Author: WebFlash

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.