0
votes

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.

3

3 Answers

3
votes

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');
});

DEMO

1
votes

Use:

e.stopPropagation();

or

return false; 

in child click handler to prevent event propagation from parent events.

0
votes

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');
});

--DEMO--