0

I want to capture clicks outside an HTML tag. For example I have this HTML:

<body> 
 <div>
  <ul>
   <li id="button">
   </li>
  </ul>
 </div>
</body>

The #button is a smallest square in the middle of the page. Once user clicks outside it something happens, click inside and nothing should happen.

This JS doesn't work because of event propagation:

jQuery('*').not('li#button').click(...);

so my click event eventually fires on ul, div and body triggering the event. I can't use this:

jQuery('*').click(function(e) {
 e.stopPropagation();
 if(e.(...)) {}
})

because other events on the page stop working.

What's the other way of achieving this?

Alan
  • 1,322
  • 1
  • 21
  • 36
  • possible duplicate of [How to detect a click outside an element?](http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element) – idmean Aug 25 '14 at 10:31

2 Answers2

0
$(document).bind('click', function(e) {
    if($(e.target).closest('#button').length == 0) {
        // yourlogic
    }
});

Also check How to detect a click outside an element?

Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0
$(document).click(function(e){
e.stopPropagation();
if($(e.Target).attr(id) != "button"){
    // Your logic
    }
});
Jayant
  • 114
  • 3
  • 8