Catch the click event on any element inside a div

I have divcontaining a bunch of elements. This one divwill be hidden (animated fadeOut()) if the screen size is less than 767 pixels. But if the user clicks on any element inside this div, I want to stop fadeOut().

But as I see it right now, I need to add a click event for every element that I have in this div. Isn't there a more elegant way to catch all click events inside div?

+4
source share
2 answers

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 triggered the click event is the same to which it is bound.

+10

, click. , , , . Stop().

$('#container').children().on('click', function (e) {
  
     //apply jQuery 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>
Hide result
+2

All Articles