Skip to content

Instantly share code, notes, and snippets.

@bogdanpopa90
Created March 29, 2017 13:22
Show Gist options
  • Save bogdanpopa90/57baf95fb6a580b243c00064cf84e732 to your computer and use it in GitHub Desktop.
Save bogdanpopa90/57baf95fb6a580b243c00064cf84e732 to your computer and use it in GitHub Desktop.
Detecting outside clicks of an element using JavaScript
/* Verify clicks outside .target-element */
$('.target-element').outside('click', function() {
// do something
}
/* Function that detect outside clicks */
(function($){
$.fn.outside = function(ename, cb){
return this.each(function(){
var self = this;
$(document).bind(ename, function tempo(e){
if(e.target !== self && !$.contains(self, e.target)){
cb.apply(self, [e]);
if(!self.parentNode) $(document.body).unbind(ename, tempo);
}
});
});
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment