0

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.

Andreas Baran
  • 669
  • 1
  • 12
  • 27

3 Answers3

3

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

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • 1
    Thank it worked - actually I had seen the answer another place on stackoverflow, but I had used it wrong, so it helped that you made an example:-) – Andreas Baran May 23 '14 at 10:48
1

Use:

e.stopPropagation();

or

return false; 

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

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • 1
    "return false" is not same as "e.stopPropagation()". "return false" is same as "e.preventDefault(); e.stopPropagation()"; – GeckoTang May 23 '14 at 10:36
0

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--

A. Wolff
  • 74,033
  • 9
  • 94
  • 155