JS Block event bubbling

Source: Internet
Author: User

When using the JS event, the outer element event may be triggered by an event in the inner element, such as clicking on the outer layer of the inner element and triggering a click, which is called event bubbling.

<div id= "Wai" >    <div id= "nei" ></div></div><script type= "Text/javascript" >$ ( Document). Ready (function(e) {    $ ("#wai"). Click (function() {            alert ( "outer click");        })    $ ("#nei"). Click (function() {            alert ("Click in the inner layer");        })});

Effect, White is the inner element Div, and blue is the outer element div:

When the white area is clicked, there are two prompts, which indicates that the inner div hit triggered, and the outer div's Click event is triggered, which occurs when the event bubbles:

To block time bubbling, you need to write a function that calls the function in the inner DIV's Click event:

To block the bubbling function:

// Block event bubbling function function stopeventbubble (event) {    var e=event | | window.event;     if (e && e.stoppropagation)    {        e.stoppropagation ();        }     Else     {        e.cancelbubble=true;    }}

The function is called in the event:

$ (document). Ready (function(e) {    $ ("#wai"). Click (function() {            alert (" The outer layer clicked ");        })    $ ("#nei"). Click (function(evt) {            alert ("Click in Layer");            Stopeventbubble (evt);         });

This prevents the event from bubbling, and clicking on the white area again will only pop up a hint:

JS Block event bubbling

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.