Phil Jackson
Phil Jackson

Reputation: 10288

jquery - prevent buildup of mousedown with overlaping elements

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?

Upvotes: 2

Views: 3530

Answers (4)

Grezzo
Grezzo

Reputation: 2263

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/

Upvotes: 0

Saeed Neamati
Saeed Neamati

Reputation: 35842

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.

Upvotes: 1

Sarath
Sarath

Reputation: 9156

$('div').click(function(e) {
      e.stopPropagation();
     //
     //do what you want
});

Upvotes: 2

karim79
karim79

Reputation: 342665

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/

Upvotes: 1

Related Questions