Detect a click outside an element

Event binding

With event binding you can listen for an click and then check to see if your element is not an target or an ancestor of that click action by using .closest().
If your element is not an target or an ancestor then that means that the click was made outside your element.
$(document).click(function(event) {
  if(!$(event.target).closest('.selector').length) {
   // some action
  }
})

Result Box
  • html
  • css
  • js

Share This:

Feel free to leave a comment!

You might alos be interested in: