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>
Share:
17,555

Related videos on Youtube

Quoter
Author by

Quoter

Updated on October 06, 2022

Comments

  • Quoter
    Quoter over 1 year

    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?

  • Tomas M
    Tomas M about 9 years
    probably add e.stopPropagation()