Skip to content

Instantly share code, notes, and snippets.

@ejb
Created December 29, 2014 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ejb/0c025989aa5c9b689b63 to your computer and use it in GitHub Desktop.
Save ejb/0c025989aa5c9b689b63 to your computer and use it in GitHub Desktop.
Tiny jQuery plugin for attaching a click event to everything except for the specified element (and its children). To use, just paste clickAnywhereElse.js into your JavaScript file.
// Written by Elliot Bentley, inspired by http://stackoverflow.com/a/3028037
$.fn.clickAnywhereElse = function(callback) {
var className = '.'+this.attr('class').replace(/ /g,'.');
$('html').click(function(event){
if ( !$(event.target).closest( className ).length ) {
callback();
}
});
};
// This hides the element `.popover` when anything else is clicked.
$('.popover').clickAnywhereElse(function(){
$(this).hide();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment