jQuery: more than one handler for same event
jQuery's .bind() fires in the order it was bound:
When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.
Source: http://api.jquery.com/bind/
Because jQuery's other functions (ex. .click()
) are shortcuts for .bind('click', handler)
, I would guess that they are also triggered in the order they are bound.
Suppose that you have two handlers, f and g, and want to make sure that they are executed in a known and fixed order, then just encapsulate them:
$("...").click(function(event){
f(event);
g(event);
});
In this way there is (from the perspective of jQuery) only one handler, which calls f and g in the specified order.
You should be able to use chaining to execute the events in sequence, e.g.:
$('#target')
.bind('click',function(event) {
alert('Hello!');
})
.bind('click',function(event) {
alert('Hello again!');
})
.bind('click',function(event) {
alert('Hello yet again!');
});
I guess the below code is doing the same
$('#target')
.click(function(event) {
alert('Hello!');
})
.click(function(event) {
alert('Hello again!');
})
.click(function(event) {
alert('Hello yet again!');
});
Source: http://www.peachpit.com/articles/article.aspx?p=1371947&seqNum=3
TFM also says:
When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.
Both handlers will run, the jQuery event model allows multiple handlers on one element, therefore a later handler does not override an older handler.
The handlers will execute in the order in which they were bound.