Created
March 29, 2017 13:22
-
-
Save bogdanpopa90/57baf95fb6a580b243c00064cf84e732 to your computer and use it in GitHub Desktop.
Detecting outside clicks of an element using JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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