Close a menu or element when clicked anywhere
Often we have a menu, modal or any other element that we want to close when you click outside of it. Therefor this little snippet that’s using jQuery.
1
2
3
4
5
6
7
8
$('html').click(function (e) {
var offTarget = $(".offTarget"); // you can add this class to button and menu so it stays clickable //
if (!offTarget.is(e.target) && offTarget.has(e.target).length === 0) {
if($('#menu').is(':visible')){
$('#closeTrigger').trigger('click'); // simulate click on close button //
}
}
});
This post is licensed under CC BY 4.0 by the author.