Reputation: 1587
I have some div called mydiv. I have a click event attached to it. Inside of the div I have a link. I want the event not to be triggered after clicking on the link. Smth like
$(document).on('click', '#mydiv a', function(){
// How to disable parent's event here?
});
Thank you!
Upvotes: 2
Views: 2404
Reputation: 20250
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!');
});
Upvotes: 3
Reputation: 966
This should do what you're looking for:
$(document).on('click', '#mydiv a', function(e){
// How to disable parent's event here?
e.stopPropagation();
});
Upvotes: 2
Reputation: 7076
Try this so you can use single JQuery
HTML
<div id="mydiv">
<span> Hello, How are you? </span>
<a id="alink" href="#"> Click ME </a>
</div>
JQUERY
$(document).on('click', '#mydiv', function(event){
alert("You clicked on Div Span");
}).children().find("#alink").click(function(e) {
return false;
});
Upvotes: 0