How to have click event ONLY fire on parent DIV, not children?
If the e.target
is the same element as this
, you've not clicked on a descendant.
$('.foobar').on('click', function(e) {
if (e.target !== this)
return;
alert( 'clicked the foobar' );
});
.foobar {
padding: 20px; background: yellow;
}
span {
background: blue; color: white; padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='foobar'> .foobar (alert)
<span>child (no alert)</span>
</div>
There's another way that works if you don't mind only targeting newer browsers. Just add the CSS
pointer-events: none;
to any children of the div you want to capture the click. Here's the support tables
http://caniuse.com/#feat=pointer-events