Reputation: 769
Consider the following snippet:
<div class="div-outer">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<div class="div-inner" style="background:red">
Curabitur hendrerit vehicula erat, ut gravida orci luctus vitae.
</div>
</div>
Now suppose the outer div has a live click
associated with it. How do I make sure that the live click
is not triggered when I click
anywhere in the inner div
?
Edit:
Here's the JS as requested
$(".div-outer").live("click",function(){alert("hi")});
This should not be triggereed when clicking on ".inner-div"
Upvotes: 38
Views: 34620
Reputation: 17217
An alternative solution is to add a CSS Pointer Events rule to the child element:
CSS:
#childElement {
pointer-events: none;
}
JavaScript:
document.getElementById("childElement").style.pointerEvents = "none";
Upvotes: 12
Reputation: 105876
You have to add an event listener to the inner child and cancel the propagation of the event.
In plain JS something like
document.getElementById('inner').addEventListener('click',function (event){
event.stopPropagation();
});
is sufficient. Note that jQuery provides the same facility:
$(".inner-div").click(function(event){
event.stopPropagation();
});
or
$(".inner-inner").on('click',function(event){
event.stopPropagation();
});
Upvotes: 46
Reputation: 363
use stopPropagation in your js file
$(".eventclick").click(function(e) {
e.stopPropagation();
});
Upvotes: 0
Reputation: 57312
you can do this by add a click event on the inner div and use either return false;
or event.stopPropagation();
$(".div-inner").click(function(){
return false;
})
or
$(".div-inner").click(function(event){
event.stopPropagation();
})
Upvotes: 1
Reputation: 15433
Create new click
listener for the inner div and call the event.stopPropagation()
in that new event.
like
$('div-outer').on('click','div-inner',function(e){
e.stopPropagation();
});
Upvotes: 2