jQuery question
What happens if I bind two event handlers to same event and same element:
For example:
var elem = $("...")
elem.click(...);
elem.click(...);
Later wins or both handlers will be run?
What happens if I bind two event handlers to same event and same element:
For example:
var elem = $("...")
elem.click(...);
elem.click(...);
Later wins or both handlers will be run?
Both handlers get called.
You may be thinking of inline event binding (eg "onclick=..."
), where a big drawback is only one handler may be set for an event.
jQuery conforms to the DOM Level 2 event registration model:
The DOM Event Model allows registration of multiple event listeners on a single EventTarget. To achieve this, event listeners are no longer stored as attribute values
Both handlers will run, the jQuery event model allows multiple handlers on one element, therefore a later handler does not override an older handler.
I don't believe the order can be determined/trusted, so don't rely on the order.
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