Catch click event on any element inside a div
17,555
Solution 1
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.
Solution 2
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>
Related videos on Youtube
Author by
Quoter
Updated on October 06, 2022Comments
-
Quoter over 1 year
I have a
div
that contains a bunch of elements. Thisdiv
will be hidden (animatedfadeOut()
) if the screen size is smaller than 767px. But if the user clicks on any of the element inside thisdiv
, I want to stop thefadeOut()
.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 adiv
? -
Tomas M about 9 yearsprobably add e.stopPropagation()