Block event bubbling in JavaScript

Source: Internet
Author: User

As shown, the gray block contains a red block, assuming we have a click-to-box event for each of the gray and red blocks, and when we click on the red block, we do not want to trigger the gray block of the bounding box event, which requires blocking the bubbling event.

The block bubbling event in IE uses the Cancelbubble property, which must be set to TRUE if the event handle wants to prevent the event from propagating to the containment object.

Non-IE browsers such as Firefox block bubbling events using the Stoppropagation () method. After the method is called, the handler that handles the event on that node is called, and the event is no longer dispatched to the other node.

Let's look at the code example:

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Event Object--block event bubbling</title></Head><Body>    <DivID= "Gray"style= "background: #ddd; width:400px;height:400px;">        <DivID= "Red"style= "background: #FF0000; width:200px;height:200px;"></Div>    </Div>    <Script>        varOgray=document.getElementById ("Gray"); varoRed=document.getElementById ("Red"); Ogray.onclick=function() {alert ("Click on the gray block! "); } Ored.onclick=function(e) {alert ("Click on the red block! "); varEvent=e||window.event; //block bubbling events, otherwise the Ogray.onclick method will be touched            if(document.all) {//IEevent.cancelbubble=true;//This property must be set to TRUE if the event handle wants to prevent the event from propagating to the containment object            }Else{                //Ff,chromeevent.stoppropagation ();//no longer distributing events            }        }            </Script></Body></HTML>

Block event bubbling in JavaScript

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.