Priorities Of jQuery Events

  • Post published:August 3, 2015

The customization of the functional features in jQuery can be enhanced to their best potential with appropriate expertise and effective technical improvisation. This helps in attaining productive results with minimal efforts and yields the most optimized solutions. In jQuery, you can bind multiple event handlers to one event for one DOM element. These will execute in the sequence they were bind. As in the example below, suppose you have DOM as:

...
<body>
 <a href='#' id='link'>Click Me</a>

 <ol id='#log'></ol>
</body>
...

JavaScript is as:

$('#link').bind('click', function(event){
 $('#log').append("<li>First Handler</li>");
});
$('#link').bind('click', function(event){
 $('#log').append("<li>Second Handler</li>");
});

When you click on the link, you will get output something like below:

1. First Handler
2. Second Handler

That’s the standard sequence of event binding. Let’s suppose if we change the code of first event handler to this:

$('#link').bind('click', function(event){
 $('#log').append("<li>First Handler</li>");
 event.stopImmediatePropogation();
});

In this case second event handler will not execute, because first have stopped event propagation. To make it executable, we need to change the priority of events binding, so that second event handler will execute first and it must not be stopped by first handler. It is not available to jQuery by default, so we have to create a custom method for it as follows:

$.fn.bindFirst = function(name, fn) {
 this.on(name, fn);
 this.each(function() {
 var handler, handlers;
 handlers = $._data(this, 'events')[name.split('.')[0]];
 handler = handlers.pop();
 handlers.splice(0, 0, handler);
 });
};

Now lets use our new method:

$('#link').bind('click', function(event){
 $('#log').append("<li>First Handler</li>");
});
$('#link').bindFirst('click', function(event){
 $('#log').append("<li>Second Handler</li>");
});

Now we the get output now like this:

1. Second Handler
2. First Handler

Note here that the second handler changed its priority to first and executed before the first handler. This is useful in many situations where some plugins bind the event and then stop its propagation.