bsr
bsr

Reputation: 58662

jquery callback specificity


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

Answers (3)

BrunoLM
BrunoLM

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

Peter Olson
Peter Olson

Reputation: 142921

Both events will be triggered, first the div, and then the document click.

Upvotes: 2

alex
alex

Reputation: 490233

It will bubble up the DOM tree and call all other events of that type.

You can stop this with event.stopPropagation().

Your example

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

Related Questions