An introduction to preventing bubbling events in jQuery

  • 2020-03-30 02:39:34
  • OfStack

A brief introduction to bubbling events

When we click on a control, the execution continues if the parent control that includes the control also has a click event.
For example, div a has a click event. When you click a, the alert appears twice. This phenomenon is called a bubbling event.

This event bubbles from the original element all the way to the top of the DOM tree.
Target element: the target element of any event is the original element, which in our case is the button,
And it appears as an attribute in our element object. With event proxies we can add event handlers to an element,
Wait for an event to bubble up from its child elements, and it is easy to know which element the event starts from.
Blur, focus, load, and unload cannot bubble like other events. Blur and focus can actually be obtained with event capture rather than event bubbling (in other browsers besides IE).

2. Prevent jQuery events from bubbling

At the beginning of the jquery.event documentation, you learn that the jquery.event object is a W3C standard Event object, and jquery.event eliminates the need to check for compatibility with IE.
JQuery.Event provides a very simple way to stop Event bubbling: event.stoppropagation ();

     // do something

But this method doesn't work for events bound with live, and you need an easier way to stop them from bubbling: return false;

$(this).after("Another paragraph!");
return false;  });

Terminate bubble function compatible with multiple browsers:

   function stopDefault(e) {
        //Block default browser action (W3C)
        if (e && e.preventDefault)
        //The way to block the default action of the function in IE
            window.event.returnValue = false;
        return false;

Use the event.tatget property to specify the event object

The variable event in the event handler holds the event object. The event.tatget attribute holds the target element of the event. This property is specified in the DOM API, but not implemented by all browsers. JQuery extends this event object as necessary so that it can be used in any browser., you can determine which element in the DOM received the event first. Furthermore, we know that this refers to the DOM element that handles the event.

The event.tatget property is used to specify the event object

The code to prevent bubbling is as follows:

$(document).ready(function() {
        if( == this)
            $('switcher .button').toggleClass('hidden');

Related articles: