Last active
January 3, 2016 13:39
-
-
Save richardscarrott/8470929 to your computer and use it in GitHub Desktop.
jquery.clickoutside.js
This file contains 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
/* | |
* 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