I have a div
that contains a bunch of elements. This div
will be hidden (animated fadeOut()
) if the screen size is smaller than 767px. But if the user clicks on any of the element inside this div
, I want to stop the fadeOut()
.
But as how I see it right now, I'll have to add a click event for each element I have inside this div
. Isn't there a more elegant way to catch all click events inside a div
?
You can do something like this:
$('#container').on('click', function (event) {
if (event.target != this) {
alert('You clicked a descendent of #container.');
} else {
alert('You actually clicked #container itself.');
}
});
This checks to see if the element that initiated the click event is the same exact one it's attached to.
This is just an extension to Bill Chriswell's answer, where children of the container's are listened for click event. To stop the animation you probably need to use .stop() method.
$('#container').children().on('click', function (e) {
//apply jQuery's stop() method here
alert("children");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="container">
container
<span>span 1</span><span> span 2</span>
</div>
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