Skip to content

Instantly share code, notes, and snippets.

@richardscarrott
Last active January 3, 2016 13:39
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 richardscarrott/8470929 to your computer and use it in GitHub Desktop.
Save richardscarrott/8470929 to your computer and use it in GitHub Desktop.
jquery.clickoutside.js
/*
* invokes 'focusout' / 'blur' type effect on any element
*
* NOTE: binds to html element so ensure namespace is passed in for manual unbinding.
*/
(function ($, undefined) {
var defaults = {
namespace: 'clickOutside', // namespace to unbind at later time (currently manual)
live: false, // set to true if contents of element changes throughout the pages life cycle
callback: $.noop
};
$.fn.clickOutside = function (options) {
var options = $.extend({}, defaults, options);
return this.each(function () {
var el = $(this),
allowed = !options.live ? el.find('*').andSelf() : undefined,
target;
$('html').on('touchstart.' + options.namespace + ' mousedown.' + options.namespace, function (e) {
target = $(e.target);
// check target isn't container or child of
if (target.filter(allowed === undefined ? el.find('*').andSelf() : allowed).length === 0) {
options.callback.call(target, arguments);
}
});
// Not working with scrollbars or anchor links...
// $(this)
// .attr('tabindex', -1)
// .focusout(function () {
// if ($.isFunction(callback)) {
// callback.apply(this, arguments);
// }
// });
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment