2

lets say I have a div nested withing another div and I have a mousedown event to trigger an alert when any of the divs are clicked on. Naturaly the alert displays twice with a single click as the divs are nested. How can I prevent this to alert only once?

Phil Jackson
  • 10,238
  • 23
  • 96
  • 130
  • Where are those divs, where is your code, please share some code if you want a solution, don't just describe it. – Shef Jul 18 '11 at 11:55

4 Answers4

2
$('div').click(function(e) {
      e.stopPropagation();
     //
     //do what you want
});
Sarath
  • 9,030
  • 11
  • 51
  • 84
1

You can stop the propagation of clicks of the nested divs, which means that they won't bubble up and trigger the click handler attached to the parent divs, e.g:

// attach to all divs
$("div").mousedown(function() {
    // do stuff
});

// stop propagation for nested divs
$("div div").mousedown(function(e) {
    e.stopPropagation()
});

See http://api.jquery.com/event.stopPropagation/

karim79
  • 339,989
  • 67
  • 413
  • 406
1

When two div elements are nested we have an HTML element hierarchy. Something like:

body
   firstDiv
      secondDiv

in which, the secondDiv is embedded in firstDiv which in turn is embedded in body. Now, whenever you click on secondDiv, firstDiv is also clicked, and body is also clicked. So, if you create 3 event handlers for these 3 elements (say show 3 alerts), you get 3 alert messages. This phenomena is called bubbling up, because if you imagine that these elements are layers of water (with child elements being deeper), and consider and event (like a click) to be a bubble, when you free a bubble on lower layers, it bubbles up to the upper layers till it gets to the surface (HTML element, or even higher, document object, and window object which is the root object).

with jQuery, you can use e.stopPropagation() function to cancel bubbling. In pure JavaScript, you use return false; to stop bubbling.

Saeed Neamati
  • 35,341
  • 41
  • 136
  • 188
0

Why don't you just add the event handler to the parent div only, that way it will always get fired only once

Check out the jsFiddle: http://jsfiddle.net/aPMB3/

Grezzo
  • 2,220
  • 2
  • 22
  • 39