Created
April 12, 2016 13:23
-
-
Save subhaze/c4e85346f40dc0f350a63d34993754f0 to your computer and use it in GitHub Desktop.
event to fire when you click outside an element
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
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