34

I have a tree of divs:

<div id="a" onclick="func">
    <div id="b" onclick="func">
         <div id="c" onclick="func">
         </div>
    </div>
</div>

When a click is made on a div it makes it's children invisible - ie click on "a" will turn "b" and "c" invisible.

function func{
   if ($(childId).hasClass("visible")){
    $(childId).removeClass("visible");
    $(childId).addClass("invisible");
}

The problem is: a click on "b" will call "a"'s click and make "b" and "c" invisible. How do I disable the click on "a" using jQuery?

thanks

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Guy
  • 14,178
  • 27
  • 67
  • 88

3 Answers3

60

You can add a handler for the child that will prevent the click event from propagating up:

function handler(event) {
    event.stopPropagation();
    // now do your stuff        
}
$('#a').add('#b').click(handler);

This way clicks to '#b' will not propagate to '#a'. Neither will clicks to '#c' go to '#b', and hence not to '#a'.

illright
  • 3,991
  • 2
  • 29
  • 54
jrharshath
  • 25,975
  • 33
  • 97
  • 127
  • This is pretty cool, even works with $(".clickyClass a").click(function(e) {e.stopPropagation();}); assuming .clickyClass has a click handler – daveagp Jul 26 '11 at 15:00
  • 1
    should this also prevent from bootstrap `data-toggle="collapse"` on parent from working? because i try and fail :( – Tomer W Dec 31 '14 at 06:12
11

use

event.stopPropagation()

Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

when click on b and c

rahul
  • 184,426
  • 49
  • 232
  • 263
1

I have the following htmlstructure:

<a href="http://example.com">
    <div> 
       <button type="button">Save</button>
    </div>
</a>

and I want to prevent new page being opened when button is clicked.

I found that stopPropagation alone is not enough. The handler should also return false.

$('button').click(function(event){
        event.stopPropagation();
        save();
        return false;
});
Yuriy N.
  • 4,936
  • 2
  • 38
  • 31