0

Im trying to detect when a user clicked on the document, so:

$(document).click(function(e){ ...

When they do click on the document I wanna check if the document was clicked outside a div (including all contents inside the div)

Currently it works so that if I click outside the div it does what I want, but if I click an element inside the div it fires the outside of div event

$(document).click(function(e) {
     var target = e.target;

     if (!$(target).hasClass('classHere') {
          //do stuff
     }

}
Bobby W
  • 836
  • 8
  • 22

1 Answers1

2

In your case, you have to check if the element is inside the div element. I suppose that your div has "classHere" class. The code may be this:

$(document).click(function(e) {
     var $element = $(this); 
     if (!$element.hasClass('classHere') && !$element.parents('classHere').length) {
          //do stuff
     }

}

I check that the div has not class "classHere" and it has not parents with this class.

Regards.

Mario Araque
  • 4,562
  • 3
  • 15
  • 25