The problem you have is that the click handler bound to the div
will trigger first because the delegated event will only fire once the event has propagated right up to the document
.
In your #mydiv
click handler, check that the event.target === this
before executing any code, that way, it'll only fire when the div
has been clicked.
Something like this:
$('#mydiv').on('click', function(e) {
if (e.target === this) {
alert('div click fired!');
}
});
$(document).on('click', '#mydiv a', function(e) {
alert('anchor click fired!');
});
Edit If the only reason you're attaching an event handler to the anchor
is to prevent triggering the click handler on the div
, just check if the target is not an anchor
in the div
click handler before doing anything else:
$('#mydiv').on('click', function(e) {
if ($(e.target).is('a')) {
return;
}
alert('div click fired!');
});