Skip to content

Instantly share code, notes, and snippets.

@Ayehavgunne
Last active July 29, 2017 10:37
Show Gist options
  • Save Ayehavgunne/1aaef3abbb3daeec0120344e450c62e8 to your computer and use it in GitHub Desktop.
Save Ayehavgunne/1aaef3abbb3daeec0120344e450c62e8 to your computer and use it in GitHub Desktop.
Quick setup for clicking outside a menu to close it
//with JQuery
function clickOutsideClose(element, callback) {
$(document).mouseup(function(e) {
let container = $(element)
if (!container.is(e.target) && container.has(e.target).length === 0) {
container.hide()
if (typeof callback === 'function') {
callback()
}
}
})
}
//Vanilla JS
function click_outside_close(element, callback) {
document.addEventListener('mouseup', function close(e) {
if (element !== e.target && !element.contains(e.target)) {
element.style.display = 'none'
if (typeof callback === 'function') {
callback()
}
document.removeEventListener('mouseup', close)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment