To add a click event listener on div tag using JavaScript, we can call the addEventListener method on the selected div. to add a div with a class. Then we write: const div = document.
The :parent Selector page on jQuery says: Select all elements that have at least one child node (either an element or text). So $('div') would select all divs and $('div:parent') would select only those with 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
I did not get the accepted answer to work, but this seems to do the trick, at least in vanilla JS.
if(e.target !== e.currentTarget) return;
You can use bubbling in your favor:
$('.foobar').on('click', function(e) {
// do your thing.
}).on('click', 'div', function(e) {
// clicked on descendant div
e.stopPropagation();
});
//bind `click` event handler to the `.foobar` element(s) to do work,
//then find the children of all the `.foobar` element(s)
//and bind a `click` event handler to them that stops the propagation of the event
$('.foobar').on('click', function () { ... }).children().on('click', function (event) {
event.stopPropagation();
//you can also use `return false;` which is the same as `event.preventDefault()` and `event.stopPropagation()` all in one (in a jQuery event handler)
});
This will stop the propagation (bubbling) of the click
event on any of the children element(s) of the .foobar
element(s) so the event won't reach the .foobar
element(s) to fire their event handler(s).
Here is a demo: http://jsfiddle.net/bQQJP/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With