Skip to content

Instantly share code, notes, and snippets.

@pospi
Created September 24, 2013 00:54
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 pospi/6679006 to your computer and use it in GitHub Desktop.
Save pospi/6679006 to your computer and use it in GitHub Desktop.
Very simple jQuery event for handling unfocusing of elements when clicking outside of them.
(function($) {
var WATCH_FOCUS_ON = $();
$.event.special['clickoutside'] = {
setup: function()
{
WATCH_FOCUS_ON = WATCH_FOCUS_ON.add( this );
// bind document handler if this is the first guy being bound
if ( WATCH_FOCUS_ON.length === 1 ) {
$(document).bind( 'click.clickoutside', unfocusHandler );
}
},
teardown: function()
{
WATCH_FOCUS_ON = WATCH_FOCUS_ON.not(this);
// unbind document handler when last one removed
if ( WATCH_FOCUS_ON.length === 0 ) {
$(document).unbind( 'click.clickoutside' );
}
},
add: function(handleObj)
{
var old_handler = handleObj.handler;
// override default event.target reference with one that is applicable
handleObj.handler = function(event, elem) {
event.target = WATCH_FOCUS_ON;
old_handler.apply(this, arguments);
};
}
};
function unfocusHandler(event)
{
$(WATCH_FOCUS_ON).each(function() {
var elem = $(this);
// clicked, but not on this element and not inside it. Fire stuff.
if (this !== event.target && !elem.has(event.target).length) {
elem.triggerHandler('clickoutside', [event.target]);
}
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment