Skip to content

Instantly share code, notes, and snippets.

@subhaze
Created April 12, 2016 13:23
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 subhaze/c4e85346f40dc0f350a63d34993754f0 to your computer and use it in GitHub Desktop.
Save subhaze/c4e85346f40dc0f350a63d34993754f0 to your computer and use it in GitHub Desktop.
event to fire when you click outside an element
jQuery.event.special.outsideclick = {
setup: function(data, namespaces, handler){
var $this = $(this);
var namespace = namespaces.join('.');
function _clickHandler(e){
var handleClick = true;
var mouseUsed = 'button' in e;
if(namespace === 'mouse' && !mouseUsed){
handleClick = false;
}else if(namespace === 'trigger' && mouseUsed){
handleClick = false;
}
if(handleClick){
var clickedKid = !!$this.has(e.target).length;
if(!clickedKid && $this[0] !== e.target){
$this.trigger('outsideclick');
}
}
}
// stores handler so it can be properly removed
// in teardown process
$this.data('__outsideclickHandler__', _clickHandler);
$('body').on('click', _clickHandler);
return true;
},
teardown: function(){
$('body').off('click', $(this).data('__outsideclickHandler__'));
return true;
},
// prevents duplicate triggers from happening
// from nested elements with 'outsideclick'
noBubble: true
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment