Event bubbling definition and cancellation in JavaScript

Source: Internet
Author: User

    • Event bubbling: If element A is nested in element B, then a is clicked not only A's OnClick event will be triggered, and the onclick of B will also be triggered. The order of triggering is "from inside Out".

    Verify: Add a div, p, strong on the page, add the OnClick event response in Div, p, strong

    • Cancel Event bubbling: window.event.cancelBubble = true;//ie under the notation.

Arguments[0].stoppropagation ();//the spelling in Firefox.

Example:

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title></title>
<style type= "Text/css" >
div {
height:400px;
width:600px;
Background-color:green;
/* When the mouse moves to the position of the label, it is displayed as a hand */
Cursor:pointer;
}

p {
height:200px;
width:300px;
Background-color:pink;
Cursor:pointer;
}

Strong {
Cursor:pointer;
}
</style>
<script type= "Text/javascript";
//Register a click event for Div, p, and strong tags respectively.
//Can only be written in one onload if there are 3 onload events that only perform the last onload event.
onload = function () {
document.getElementById (' dv '). onclick = function () {
alert (this.id);
};
document.getElementById (' P '). onclick = function () {
alert (this.id);

if (arguments.length > 0) {
//Firefox cancels the bubbling event
Arguments[0].stoppropagation ();
} else {
//ie in the Cancel bubbling event
Window.event.cancelBubble = true;
}
Window.event.cancelBubble = true;
};
document.getElementById (' st '). onclick = function () {
alert (this.id);
if (arguments.length > 0) {
//Firefox Cancels the Bubbling event
Arguments[0].stoppropagation ();
} else {
//ie in the Cancel bubbling event
Window.event.cancelBubble = true;
}
};

};
</script>
<body>
<div id= "DV" >
<p id= "P" >
<strong id= "St" > This is a div tag under the P tab under the strong tag </strong>
</p>
</div>
</body>

Event bubbling definition and cancellation in JavaScript

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.