Created
September 24, 2013 00:54
-
-
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.
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
(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