2
<div id="firstDiv" style="width:1000px;height:600px;">
    <div id="secondDiv" style="width:200px;height:200px;"></div>
</div>

Both DIVs have click() events. When I click secondDiv, the click-event for firstDiv is also fired (I guess that is logic since I also clicked within firstDiv's borders). I however only want to fire the click-event for the DIV that I actually had my mouse over upon clicking.

How can I accomplish that?

Matt Welander
  • 8,234
  • 24
  • 88
  • 138
  • 3
    duplicate http://stackoverflow.com/questions/2015041/two-differents-onclick-on-two-divs-one-over-the-other – Mandar Apr 23 '13 at 20:35
  • possible duplicate of [click - only on "direct" onclicks](http://stackoverflow.com/questions/6512803/click-only-on-direct-onclicks) – Nope Apr 24 '13 at 17:18
  • [`event.stopPropagation`](http://api.jquery.com/event.stopPropagation/)? – Salman A Apr 24 '13 at 19:29

5 Answers5

10

On the inner div add:

$('#secondDiv').click(function(e){e.stopPropagation();});

.stopPropagation() will prevent the click event from bubbling up from inner div to the parent div or any other ancestor.

j08691
  • 204,283
  • 31
  • 260
  • 272
5

DOM elements by default bubbles up the events. You can stop by using stopPropagation

$('#secondDiv').on('click', function(e){
    e.stopPropagation();
});
Teja Kantamneni
  • 17,402
  • 12
  • 56
  • 86
1

You can just do this -

$('#secondDiv').click(function(event) {
    // do your stuff
    return false;
 });

return false; is the equivalent to event.stopPropagation() and event.preventDefault()

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
1

You'll want use event.stopPropagation() which will prevent the event from bubbling up to parent elements (in your case). The preventDefault looks promising but it actually prevents default actions - not bubbling.

$("#firstDiv").click(function() {
  alert("Div One");
});

$("#secondDiv").click(function(e) {
  e.stopPropagation();
  alert("Div Two");
});

Demo of both here.

Brandon Buck
  • 7,177
  • 2
  • 30
  • 51
0

You can use event.stopPropagation() for this bubbling. Something like this:

$("secondDiv").click(function(event) {
  event.stopPropagation();
   //Write your logic here
});

For more information on this refer to the documentation HERE

Raman
  • 1,336
  • 10
  • 13