<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 acplish that?
<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 acplish that?
Share Improve this question asked Apr 23, 2013 at 20:33 Matt WelanderMatt Welander 8,57825 gold badges96 silver badges146 bronze badges 3- 3 duplicate stackoverflow./questions/2015041/… – Mandar Commented Apr 23, 2013 at 20:35
- possible duplicate of click - only on "direct" onclicks – Nope Commented Apr 24, 2013 at 17:18
-
event.stopPropagation
? – Salman Arshad Commented Apr 24, 2013 at 19:29
5 Answers
Reset to default 10On 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.
DOM elements by default bubbles up the events. You can stop by using stopPropagation
$('#secondDiv').on('click', function(e){
e.stopPropagation();
});
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()
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.
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