Js bubble event blocking implementation code

Source: Internet
Author: User

1. event Target

Now, the variable event in the event handler stores the event object. The event.tar get attribute stores the target element of the event. This attribute is specified in the dom api but is not implemented by all browsers. JQuery makes necessary extensions to this event object so that this attribute can be used in any browser. Through .tar get, you can determine the elements in the DOM that receive the event first (that is, the actually clicked element ). Furthermore, we know that this references the DOM elements used to process events, so you can write the following code:
Copy codeThe Code is as follows:
$ (Document). ready (function (){
$ ('# Switcher'). click (function (event ){
$ ('# Switcher. click'). toggleClass ('hiddy ');
})
})

$ (Document). ready (function (){
$ ('# Switcher'). click (function (event ){
If(event.tar get = this ){
$ ('# Switcher. click'). toggleClass ('hiddy ');
}
})
})
 
The Code ensures that the clicked element is <div id = "switcher">, rather than other descendant elements. Now, clicking the button does not collapse the style converter, and clicking the border triggers the collapse operation. However, clicking a tag does not happen because it is also a descendant element. In fact, we can not put the check code here, But modify the button behavior to achieve the goal.

2. Stop event Propagation

The event object also provides a. stopPropagation () method, which can completely prevent event bubbles. Similar to .tar get, this method is also a pure JavaScript feature, but it cannot be safely used in cross-browser environments. However, as long as we use jQuery to register all event handlers, we can safely use this method.
Next, we will delete the prompt statement event.tar get = this and add some code to the button's click handler:

Copy codeThe Code is as follows:
$ (Document). ready (function (){
$ ('# Switcher. click'). click (funtion (event ){
//......
Event. stopPropagation ();
})
})

As before, you need to add a parameter for the function used as a click handler to access the event object. Then, by simply calling event. stopPropagation (), all other DOM elements can be prevented from responding to this event. In this way, the event that you click the button will be processed by the button and will only be processed by the button. Click elsewhere in the style converter to collapse and expand the entire area.

3. Default operation

If we register the click event handler to an anchor element instead of an outer <div>, we have to face another problem: When you click the link, the browser loads a new page. This behavior is not the same as the event handler we are discussing. It is the default operation for clicking the anchor element. Similarly, when you press the Enter key after editing the form, the submit event of the form is triggered. After this event occurs, the form is submitted.
If we do not want to execute this default operation, it is useless to call the. stopPropagation () method on the event object because the default operation does not occur in the normal event propagation stream. In this case, the. preventDefault () method can terminate the event before the default operation is triggered.
It indicates that. preventDefault () is usually used after some verification is completed in the event environment (). For example, during form submission, we will check whether required fields are filled in by the user. If the user does not fill in the corresponding fields, we need to prevent the default operation. We will discuss Form Verification in detail in Chapter 8th.
Event propagation and default operations are independent of each other. when either of them occurs, the other can be terminated. If you want to stop event propagation and default operations at the same time, you can return false in the event handler, which is called on the event object at the same time. stopPropagation () and. preventDefault () is short for preventDefault.

Supplement:
Copy codeThe Code is as follows:
// Click the button event (change the text style)
$ (Document). ready (function (){
$ ('# Switcher. click'). click (function (){
$ ('Body'). removeClass ();
If (this. id = 'switcher-narrow '){
$ ('Body'). addClass ('narrow ');
}
Else if (this. id = 'switcher-large '){
$ ('Body'). addClass ('large ');
}

$ ('# Switcher. click'). removeClass ('selected ');
$ (This). addClass ('selected ');
});
});

// Click the outer div event (hide button)
$ (Document). ready (function (){
$ ('# Switcher'). click (function (){
$ ('# Switcher. click'). toggleClass ('hiddy ');
});
});

The problem is that the hidden button event is triggered when the button is clicked. This is caused by event bubbling.
To prevent event bubbles, you need to add a parameter to the hidden button function:
Copy codeThe Code is as follows:
$ (Document). ready (function (){
$ ('# Switcher'). click (function (even ){
If(even.tar get = this ){
$ ('# Switcher. click'). toggleClass ('hiddy ');
}
});
});

The even.tar get attribute stores the target element of an event. It can be determined that the DOM first receives the event element. In this case, the Code ensures that the clicked <div id = "switcher"> is not its descendant element.

You can also modify the button action to achieve the goal.
Copy codeThe Code is as follows:
$ (Document). ready (function (){
$ ('# Switcher. click'). click (function (even ){
$ ('Body'). removeClass ();
If (this. id = 'switcher-narrow '){
$ ('Body'). addClass ('narrow ');
}
Else if (this. id = 'switcher-large '){
$ ('Body'). addClass ('large ');
}

$ ('# Switcher. click'). removeClass ('selected ');
$ (This). addClass ('selected ');
Even. stopPropagation ();
});
});

Use JS to prevent event bubbling

Event bubbling: when an event on an element is triggered, for example, if you click a button, the same event will be triggered among all the ancestor elements of that element. This process is called event bubbling, which starts from the original element until the top layer of the DOM tree.
Javascript can be used to prevent JS events from bubbling. Because of the differences in browsers, The JS Writing of IE and FF is a little different.
IE uses cancelBubble = true to block it, while FF uses the stopPropagation method.
The complete code is as follows:
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> untitled document </title>
<Script type = "text/javascript">
Function aaaclick (){
Alert ("td click ");
}
Function bbbclick (evt ){
Alert ("td click ");
If (window. event ){
Event. cancelBubble = true;
} Else if (evt ){
Evt. stopPropagation ();
}
}
Function trclick (){
Alert ("tr click ");
}

Function tableclick (){
Alert ("table click ");
}
</Script>

<Style type = "text/css">
<! --
. Tab {
Border: 1px solid # 0066FF;
Cellpadding: 0px;
Cellspacing: 0px;
}
. Tab td {
Border: 1px solid # 0066FF;
}
-->
</Style>
</Head>

<Body>
<P> clicking aaaa triggers the onclick event of the upper layer. Clicking bbbb does not trigger the onclick event of the upper layer. </p>
<Table width = "204" onclick = "tableclick ()" class = "tab">
<Tr>
<Td width = "96"> </td>
<Td width = "96"> </td>
</Tr>
<Tr onclick = "trclick ()">
<Td onclick = "aaaclick ()"> aaaa </td>
<Td onclick = "bbbclick (event)"> bbbbb </td>
</Tr>
<Tr>
<Td> </td>
<Td> </td>
</Tr>
</Table>
</Body>
</Html>

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.