Preventing Event Propagation and Bubbling in jquery

To stop event propagation (either by stopping event capturing or event bubbling), we have to tell the event handler to stop propagating further, and this can be achieved by using the following jQuery code:

event.stopPropagation();

event.stopPropagation() works in all the browsers except for IE prior to version 9.0. For earlier IE versions, you can set the cancelBubble property available with IE to true, as shown in the following JavaScript code:

event.cancelBubble =true;

A one-line way to achieve cross-browser code is shown in the following code snippet:

event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true);

Now that you are familiar with the functioning of event.stopPropagation, we will take up another method provided by the jQuery framework—the preventDefault method. This discussion will help you to understand the difference between the two methods, and you will be able to gain a clear understanding of which method to use in which circumstance.

The preventDefault method is called on the event object and is used to prevent the default action that the browser takes on at the occurrence of an event.

For example, have a look at the following code, in which we have a button element inside of a div element, and we program an event handler to respond to a mouse click event on both of the elements:

<div id="apress">
<a id="author">Click Me</a>
</div>

The jQuery code supporting the example is as shown:

$("#apress").click(function() {
alert("Apress!!");
});

$("#author").click(function(event) {
alert("Authors!!");
event.preventDefault();
});

So, in the code setup we provided, when a click event occurs, the anchor element’s click handler is called, followed by the div’s click handler, because the preventDefault method only prevents the default action associated with the anchor element from occurring but not the event from propagating to other parts of the DOM. Hence, you will see two alert messages: “Authors!!“, followed by “Apress!!”.

As a further attempt to clearly demarcate the difference between the uses of the two methods, we recommend that you have a look at the following code snippet (which is just a one-line addition to the previous example):

$("#apress").click(function() {
alert("Apress!!");// mouse click on div element
});

$("#author").click(function(event) {
alert("Authors!!");
event.preventDefault();
event.stopPropagation();
});

Here, not only is the default action prevented from occurring, but the event is also stopped from propagating throughout the DOM. The output in this case would just be “Authors!!”.

Handling the Event Queue

As you know, a queue in general terms, is a line or sequence of people awaiting their turn to be attended, such as when people line up to board a bus at a bus stop.

In computer science, a queue is an abstract data type in which the first element is inserted at one end, called REAR, and an existing element is deleted from the other end, called FRONT. This makes up a FIFO (First In, First Out) rule, which means the element inserted first will be removed first. Examples of queues can be seen in call center phone systems, serving requests on a single shared resource, such as CPU task scheduling, printer queue, etc.

In terms of event queues, there is/are one or more function/functions waiting to run. A queue can be used for creating animations in most cases, but you can use one anytime you have to run a sequence of functions. Our current context assumes a similar meaning of the term queue. In the following text discussion, we provide you additional details about how queues are handled in jQuery.

How Handling Works in a jQuery Event Queue

Event queues can be handled by a jQuery internal queue handler, which is attached to a particular event on a particular element. The first time you bind an event to that element, it initializes the queue and uses the JavaScript method addEventListener to bind the event to jQuery’s generic event-handling function. When the event is triggered, the function uses event.target to determine which element it is, and then it finds the queue of handlers associated with it and calls them in the sequence.

The .on() method utilizes this mechanism and takes advantage of event bubbling. When an event occurs, it is triggered on the specific target element and also on all its containing elements, including child elements as well as the dynamically added elements. When you bind the handler to a container, it saves the selector string in the queue entry. When it is processing that entry in the handler queue, it tests whether event.target (which is still the specific element that you clicked) matches the selector and then executes the handler function. This mechanism allows you to bind handlers for elements that have not yet been added to the DOM. This is particularly useful when you have a list of elements that is updated dynamically via an Ajax call (for example, adding rows to a table or adding a particular div on some event).

Now that we have discussed how the internal mechanism of jQuery event queue works, let’s discuss the queue() method provided by the jQuery framework.

The jQuery queue() Method

An element can have several queues. The queue() method is used to show the queue of functions to be executed on the set of matched elements.

The signature is pretty simple to understand:

$(selectorElement).queue(queueName);

In this signature, the parameter queueName is optional.

The default queue in jQuery is fx, and it has some special properties that are not shared with other queues. So, when using the queue method as $(elem).queue( function() {} ), the fx queue will automatically de-queue the next function and run it automatically if the queue hasn’t started.

Note  The fx queue is used by the .animate() method in particular.

If you are using any custom queue, you must de-queue the function, as it will not start automatically.

Let’s consider an example of an event queue that has many events to perform.

//HTML
<div class='relative'>
<a class='event-queue'>Click Here</a>
</div>

//CSS
<style>
.relative {
position: relative;
}

.event-queue {
background: green;
border-radius: 4px;
color: #fff;
display: inline-block;
left: 0;
padding: 5px;
position: absolute;
top: 60px;
}
</style>

//jQuery
$('.event-queue').on('click', function () {
$(this).animate({left: '+=400'}, 4000)
.slideToggle(1000)
.slideToggle('fast')
.animate({ left: '-=400'}, 1500)
.hide('slow')
.show(1200)
.slideUp('slow')
.slideDown('slow')
.animate({ left: '+=400'}, 4000);
});

As you can see from the preceding code, we have set up a queue of events waiting to run at the selector click event. The output of the code is an animated Click Here button that slides from side to side at varying speeds and also appears and disappears.

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares