Explore JavaScript's event bubbling

Source: Internet
Author: User

There are two very important features in the Javasciprt event: event bubbling and the target element.

When an event on an element is triggered, such as a mouse click on a button, the same event will be triggered in all ancestor elements of that element. This process is known as event bubbling, which bubbles to the top of the DOM tree from the beginning of the original element. Tiantai Yi Zhuang Metallurgy

The target element of any event is the first element, in our example, the button, and it appears as an attribute in our element object. With the event agent, we can add an event handler to an element, wait for an event to bubble up from its child element, and be able to easily tell which element the event started from.

Bubbling and capturing of events

The capture is from the ancestor element to the subordinate element, bubbling from the subordinate element to the ancestor element.

In IE, each element and window object has two methods: Attachevent () and DetachEvent (). Attachevent () is used to attach an event handler function to an event. The DetachEvent () is used to separate the event handler functions.

var Fnclick = function () {alert ("clicked!");} var odiv = document.getElementById ("Div1"); Odiv.attachevent ("onclick", Fnclick); Odiv.detachevent ("onclick", Fnclick );
What are the benefits of bubbling events?

Imagine now we have a 10-column, 100-row HTML table that you want to do when the user clicks on a cell in the table. For example, I once had to make each cell in the table editable when clicked. Adding an event handler to these 1000 cells creates a big performance problem and can lead to memory leaks and even browser crashes. Conversely, with the event proxy, you just need to add an event handler to the table element, which can intercept the click event and determine which cell is clicked.

The code is simple, and all we have to worry about is how to detect the target element. Let's say we have a TABLE element, the ID is "report", and we add an event handler for this table to call the Editcell function. The Editcell function needs to determine the target element of the event that is passed to the table. It is possible to use this function in some of the functions we are writing, so let's put it in a separate function called Geteventtarget:

function Geteventtarget (e) {   e = e | | window.event;   return E.target | | E.srcelement;}

E This variable represents an event object, we just need to write a little cross-browser code to return the target element, In IE, the target element is placed in the Srcelemtn attribute or the Event.toelement attribute, while in other browsers it is the target or Event.relatedtarget attribute.

The next step is the Editcell function, which is called to the Geteventtarget function. Once we have the target element, the rest is to see if it is the element we need.

function Editcell (e) {   var target = Geteventtarget (e);   if (target.tagName.toLowerCase () = = = ' td ') {     //do SOMETHING with the CELL   }}

In the Editcell function, we determine whether it is a table cell by examining the label name of the target element. This check may be a bit simplistic, if it is another element in the target element cell? We need to make a little bit of changes to the code so that it can find the parent TD element. What if there are some cells that don't need to be edited? In this case we can add a specified style name to those cells that cannot be edited, and then check to see if it does not contain the style name before turning the cell into an editable state. Choices are always diverse, and you just need to find the one that's right for your application.

Advantages and disadvantages of event bubbling

There are fewer event handlers that need to be created and reside in memory. This is an important point, so that we improve performance and reduce the risk of crashes.

There is no need to rebind the event handler after the DOM update. If your page is dynamically generated, for example through Ajax, you no longer need to add or remove event handlers when the element is loaded or unloaded.

Potential problems may not be obvious, but once you notice them, you can easily avoid them: Your event management code is at risk of becoming a performance bottleneck, so try to make it short and simple.

Not all events can bubble.

Blur, focus, load, and unload cannot bubble like any other event. In fact blur and focus can be obtained using event capture rather than event bubbling (in browsers other than IE).

It is important to note that if your code handles MouseMove events, you are at a greater risk of encountering a performance bottleneck because the MouseMove event triggers very often. Mouseout, however, becomes difficult to manage with event proxies because of its bizarre behavior.

Avoid event bubbling

In IE, solve the problem is very simple, with Onmouseenter, OnMouseLeave to replace onmouseover, onmouseout on the line, their role is basically the same, the former will not occur bubbling. But there are no two events under Firefox.

Window.event.cancelBubble = True (IE)   event.stoppropagation ()  Event.preventdefault () (Firefox)

Blocking bubbling behavior is different within IE and FF browsers. Use Stoppropation () in Cancelbubble,ff in IE.

Block jquery events from bubbling

jquery's event triggering on the DOM has bubbling properties. Sometimes this feature can be used to reduce duplication of code, but sometimes we don't want events to bubble. This time will stop jquery.event bubbling.

At the beginning of Jquery.event's documentation, it was known that the Jquery.event object was an event object that met the standards of the Internet, while jquery.event removed the steps to check for compatible ie.

Jquery.event provides a very simple way to prevent event bubbling: event.stoppropagation ();

$ ("P"). Click (Function (event) {     event.stoppropagation ();     Do something})

However, this method has no effect on events that use live bindings and requires an easier way to prevent events from bubbling: return false;

$ (this). After ("another paragraph!"); return false;  });

Explore JavaScript's event bubbling

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.