Js bubbling event prevents code _javascript tips

Source: Internet
Author: User

1. Event Target

The event object is now stored in the event handler. The Event.target property holds the target element in which the event occurred. This attribute is specified in the DOM API, but is not implemented by all browsers. jquery makes the necessary extensions to this event object to be able to use this property in any browser. With. Target, you can determine the element in the DOM that receives the event first (that is, the element that is actually clicked). Also, we know that this refers to the DOM element that handles the event, so you can write the following code:

Copy Code code as follows:

$ (document). Ready (function () {
$ (' #switcher '). Click (Function (event) {
$ (' #switcher. Button '). Toggleclass (' hidden ');
})
})

$ (document). Ready (function () {
$ (' #switcher '). Click (Function (event) {
if (event.target==this) {
$ (' #switcher. Button '). Toggleclass (' hidden ');
}
})
})

The code at this point ensures that the clicked element is <div id= "switcher" >, not other descendant elements. Now, clicking the button does not collapse the style converter, and clicking the border triggers the collapse operation. However, clicking the label also doesn't happen because it is also a descendant element. In fact, instead of putting the check code here, we can achieve the goal by modifying the behavior of the button.

2. Stop Event Propagation

The event object also provides a. Stoppropagation () method that can completely block event bubbling. Like. Target, this method is also a pure JavaScript feature, but it is not safe to use in a cross-browser environment. However, we can safely use this method as long as we register all the event handlers through jquery.
Below, we delete the check statement just added Event.target = = This and add some code to the button's click handler:

Copy Code code as follows:

$ (document). Ready (function () {
$ (' #switcher. Button '). Click (Funtion (Event) {
......
Event.stoppropagation ();
})
})

As before, you need to add a parameter to 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. As a result, the button's event is handled by the button and is handled only by the button. Click elsewhere in the style converter to collapse and expand the entire area.

3. Default Action

If we register a click event handler with an anchor element instead of an outer <div>, there is another problem: when the user clicks the link, the browser loads a new page. This behavior is not the same concept as the event handler we are discussing, it is the default action for clicking an anchor element. Similarly, when a user presses the ENTER key after editing the form, it touches the submit event of the publication, and the form submission does not actually occur after the event occurs.
If we do not want to perform this default action, it also does not help to invoke the. Stoppropagation () method on the event object because the default action does not occur in the normal event propagation stream. In this case, the. Preventdefault () method can terminate the event before the default action is triggered.
Tip When some validation is done in the environment of an event, the. Preventdefault () is usually used. For example, during the form submission, we check whether the user has filled in the required fields, and if the user does not fill in the fields, then the default action will need to be blocked. We will discuss form validation in the 8th chapter in detail.
Event propagation and default operations are two separate sets of mechanisms that can terminate on either side when they occur. If you want to stop event propagation and the default action at the same time, you can return false in the event handler, which is a shorthand for calling both. Stoppropagation () and. Preventdefault () on the event object.

Add:

Copy Code code as follows:

Click the button event (change the text style)
$ (document). Ready (function () {
$ (' #switcher. Button '). Click (function () {
$ (' body '). Removeclass ();
if (this.id = = ' Switcher-narrow ') {
$ (' body '). addclass (' narrow ');
}
else if (this.id = = ' Switcher-large ') {
$ (' body '). addclass (' large ');
}

$ (' #switcher. Button '). Removeclass (' selected ');
$ (this). AddClass (' selected ');
});
});

Click on button outer div Start Event (hide button)
$ (document). Ready (function () {
$ (' #switcher '). Click (function () {
$ (' #switcher. Button '). Toggleclass (' hidden ');
});
});


The problem now is that when the button is clicked, the Hidden button event is also triggered. This is caused by event bubbling.
To prevent event bubbling, you need to add a parameter for the hidden button function:
Copy Code code as follows:

$ (document). Ready (function () {
$ (' #switcher '). Click (function (even) {
if (even.target==this) {
$ (' #switcher. Button '). Toggleclass (' hidden ');
}
});
});

Even saves the event object, and the Even.target property holds the target element of the event. You can determine the element in the DOM that receives the event first. The code now ensures that the <div id= "Switcher" is clicked, not its descendant elements.

This can also be done by modifying the behavior of the button to achieve the goal.

Copy Code code as follows:

$ (document). Ready (function () {
$ (' #switcher. Button '). Click (function (even) {
$ (' body '). Removeclass ();
if (this.id = = ' Switcher-narrow ') {
$ (' body '). addclass (' narrow ');
}
else if (this.id = = ' Switcher-large ') {
$ (' body '). addclass (' large ');
}

$ (' #switcher. Button '). Removeclass (' selected ');
$ (this). AddClass (' selected ');
Even.stoppropagation ();
});
});

Block event bubbling with JS

Event bubbling: When an event on an element is triggered, such as when a mouse clicks on a button, the same event is triggered in all ancestor elements of that element. This process is called event bubbling; This event bubbles from the original element to the top of the DOM tree.
You can use JS to prevent JS event bubbling. Because of the difference between the browser IE and FF JS writing a little different.
IE uses the cancelbubble=true to block and the FF needs to use the Stoppropagation method.
Next complete code:

Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<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>

<body>
<p> Click AAAA will trigger the upper level onclick event, click BBBB will not trigger the upper onclick event </p>
<table width= "204" onclick= "Tableclick ()" class= "tab" >
<tr >
<TD width= > </td>
<TD width= > </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>

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.