Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch click event on any element inside a div

Tags:

jquery

onclick

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?

like image 961
Quoter Avatar asked Dec 12 '22 00:12

Quoter


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 initiated the click event is the same exact one it's attached to.

like image 169
Bill Criswell Avatar answered Dec 31 '22 10:12

Bill Criswell


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>
like image 26
jyrkim Avatar answered Dec 31 '22 10:12

jyrkim