Skip to content

Instantly share code, notes, and snippets.

@laktek
Created June 29, 2010 06:38
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 laktek/456875 to your computer and use it in GitHub Desktop.
Save laktek/456875 to your computer and use it in GitHub Desktop.
/**
* jQuery plugin to detect clicks outside an element
*
* Copyright (c) 2010 Vesess Inc. (vesess.com)
* Licensed under the MIT (MIT-LICENSE.txt) licenses.
*
*/
(function($){
$.fn.outsideClick = function(optional_params){
if(arguments.length <= 0)
var optional_params = {};
var namespace = optional_params["namespace"] || ""
var callback = (optional_params["callback"] && $.isFunction(optional_params["callback"])) ? optional_params["callback"] : function(){ $(this).hide() }
event_name = "mousedown"
event_name_with_namespace = (namespace != "") ? (event_name + "." + namespace) : event_name
return this.each(function(i) {
//bind an event to document
var self = this;
$(document).bind(event_name_with_namespace,
function(event){
elemIsParent = $.contains(self, event.target);
if(event.target == self || elemIsParent) return
if($.isFunction(callback))
callback.apply(self);
else
$(self).hide(); //do the default action - hide the box element
$(document).unbind(event_name_with_namespace);
});
});
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment