views:

24

answers:

2

How does the click() function in jquery work when working with multiple stacked divs?

I have one main div and another div inside of the main div, when i click on the div inside, its also considered a click on the main div, but i dont want that, i want it to only consider a click on the inside div.

<div id="main"><div id="inner"></div></div>

Lets say the main div is a lot larger and the innner div is just a small square, when i click on the inner div(small square) I dont want it to trigger anyting as if i were to click on the main div. How do I maneuver this? Thanks again!

+5  A: 

Events bubble up from the one that was clicked, through all its ancestors. Any ancestor that handles that event will have its handler fired.

What you need to do is to call event.stopPropagation() in order to prevent the event from bubbling up to its ancestor elements.

$('#inner').click(function(evt) {
    evt.stopPropagation();
    // your code
});

Another alternative is to return false; at the end of your handler.

$('#inner').click(function(evt) {
    // your code
    return false;
});

You can test it out here: http://jsfiddle.net/ZpeYr/

patrick dw
A: 
$('#inner').click(function() {  
  alert('clicked inner div'); // do something
});

you can call your inner div using using the css id.

Honshi