Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the sequence of jQuery events triggered?
The jQuery event handlers always execute in the order they were bound. With jQuery, you can also change the sequence by creating a custom function to bind handlers at the beginning of the event queue instead of the end.
Let's see how, for example, from ?
demo(1); demo(2);
We can change the sequence to ?
demo(2); demo(1);
Understanding Event Handler Sequence
By default, jQuery binds event handlers to the end of the event queue. When multiple handlers are attached to the same element for the same event, they execute in the order they were bound. To change this behavior, we need to manipulate jQuery's internal event data structure.
Example
You can try to run the following code to learn and change the sequence of jQuery events ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Custom function to bind event handlers at the beginning
$.fn.bindFirst = function(name, fn) {
this.on(name, fn);
this.each(function() {
var handlers = $._data(this, 'events')[name.split('.')[0]];
var handler = handlers.pop();
handlers.splice(0, 0, handler);
});
};
$("div").click(function() { alert("1"); });
$("div").click(function() { alert("2"); });
$("div").click(function() { alert("3"); });
$("div").click(function() { alert("4"); });
// This handler will execute first due to bindFirst
$("div").bindFirst('click', function() { alert("5"); });
});
</script>
<style>
.demo {
cursor: pointer;
border: 3px solid #FF0000;
padding: 20px;
margin: 10px;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<div class="demo">
Click here for sequence.<br>
The sequence will be: 5, 1, 2, 3, 4
</div>
</body>
</html>
When you click the div element, the alerts will appear in the sequence: 5, 1, 2, 3, 4. The bindFirst function works by first binding the event handler normally, then manipulating jQuery's internal event data to move the newly added handler to the front of the handlers array.
Conclusion
jQuery event handlers execute in the order they were bound by default, but you can change this sequence by creating custom functions that manipulate the internal event handler queue to prioritize certain handlers over others.
