Reputation: 659
I want to prevent my parent click method to fire if the user clicks on a specific child element.
Example html:
<div data-type="parent_holder" style="width:500px; height:500px;">
<div data-type="child_holder" style="width:50px; height:50px; position:absolute;">
click
</div>
</div>
Example js:
I use jquery on in my js because I attach the element dynamically to a sortable list.
$( "#sortable" ).on( "click", "[data-type=parent_holder]", function() {
alert('parent');
});
$( "#sortable" ).on( "click", "[data-type=child_holder]", function() {
alert('child');
});
So what I want is, when a user clicks on the parent_holder it should alert parent, but if the user clicks on the child_holder it should alert child, and not alert parent.
I have searched stackoverflow and I have tried many of the suggestions, like :not(), bubbling, stopPropagation(), but I can't seem to get the right result.
Upvotes: 0
Views: 156
Reputation: 82241
Use:
e.stopPropagation();
or
return false;
in child click handler to prevent event propagation from parent events.
Upvotes: 1
Reputation: 74420
If for some reason you still need the click event to bubble from child element, you could filter instead the target inside parent click handler:
$( "#sortable" ).on( "click", "[data-type=parent_holder]", function(e) {
if(!$(e.target).is('[data-type=parent_holder]')) return;
alert('parent');
});
Upvotes: 0
Reputation: 67207
Sounds like event propagation is happening in your case,
just avoid that by using event.stopPropagation()
Try,
$( "#sortable" ).on( "click", "[data-type=child_holder]", function(e) {
e.stopPropagation();
alert('child');
});
Upvotes: 3