Suppose I have a button on my web page:
<input type='button' id='myButton' value='Click me!' />
Suppose that I write the following jQuery:
$(document).ready(function() {
var button = $('#myButton');
button.click(doThis);
button.click(doThat);
}
function doThis() {
// do something
}
function doThat() {
//do something else
}
When the button is clicked, how can I know which function should execute first? Or does it depend on things beyond my control?
Suppose I have a button on my web page:
<input type='button' id='myButton' value='Click me!' />
Suppose that I write the following jQuery:
$(document).ready(function() {
var button = $('#myButton');
button.click(doThis);
button.click(doThat);
}
function doThis() {
// do something
}
function doThat() {
//do something else
}
When the button is clicked, how can I know which function should execute first? Or does it depend on things beyond my control?
Share Improve this question asked Aug 9, 2011 at 16:14 Vivian RiverVivian River 32.5k64 gold badges210 silver badges324 bronze badges 1- They almost certainly will be called in the order in which the registrations were made, but that seems like a scary thing to rely on. – Pointy Commented Aug 9, 2011 at 16:30
3 Answers
Reset to default 9The handlers are executed in the order they have been attached to the element (see the documentation):
If there are multiple handlers registered, they will always execute in the order in which they were bound.
So in your case, first doThis
and then doThat
will be executed.
Note: This only applies to jQuery. For information about pure DOM event handlers, see @StuperUser's answer.
For general information about event handling in JavaScript, I can remend the articles at quirksmode.
jQuery events will fire in order of attachment as @Felix Kling and @Kyle have said.
This is not the case outside of jQuery. According to jQuery in Action Second Edition - on the DOM Level 2 event model (e.g. using addEventListener rather than $.bind
or methods that call it)
Note that even though the handlers fire in the order they were established, this order isn't guaranteed by the standard! Testers of this code never observed an order other than the order of establishment, but it would be foolish to write code that relies on this order. Always be aware that multiple handlers established on an element may fire in random order.
Yet another reason to use jQuery.
They will execute in the order you bind them (doThis followed by doThat).