Last active
July 29, 2017 10:37
-
-
Save Ayehavgunne/1aaef3abbb3daeec0120344e450c62e8 to your computer and use it in GitHub Desktop.
Quick setup for clicking outside a menu to close it
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
//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