Reputation: 58662
Is there any specificity associated with event callback with jQuery. Say, I register a mousedown event callback on a div element, and also on the document. Which one would trigger if I click on the div? Does the order of registration matters? or the specificity (like css) matters?
thanks.
Upvotes: 2
Views: 229
Reputation: 100331
It will execute both, from inside out. Clicking in the div will fire the div event then the document. Example on jsFiddle
$(window.document).click(function(e){
alert("doc");
});
$("div").click(function(e){
alert("div");
});
You can avoid it firing other events with e.stopImmediatePropagation()
. See this example
$(window.document).click(function(e){
alert("doc");
});
$("div").click(function(e){
alert("div");
e.stopImmediatePropagation(); // prevents $(doc) from rising
});
Upvotes: 1
Reputation: 142921
Both events will be triggered, first the div, and then the document click.
Upvotes: 2
Reputation: 490233
It will bubble up the DOM tree and call all other events of that type.
You can stop this with event.stopPropagation()
.
If you assigned the events like so...
$(document).mousedown(function() { alert('document'); });
$('div').mousedown(function() { alert('div'); });
Mouse down anywhere will trigger document
's handler, and get one alert dialog with document.
Mouse down on any div
will trigger the div
's handler, and then bubble up the DOM all the way to document
where it will trigger its event handler. You will get two alert dialogs; first the div one and then the document one.
Upvotes: 5