Question:
Well I know how to identify a click in Cida of an element. I do like this:
// Fecha Sidenav
$("#Close_Sidenav").click(function() {
$("#mySidenav").hide();
});
However I need the $("#mySidenav").hide()
be executed when I click on the Close_Sidenav
element and when I click outside the mySidenav
element.
How do I do this?
For more info I'm trying to make this menu close when I click outside of it. Menu
Answer:
You can add an event window
to window
or document
and at the time of click check if event.target
is inside the menu. To optimize a little you can have a menu flag, to avoid running code if the menu is closed…
It could be something like this:
var menuAberto = false;
// Fecha Sidenav
function fechaSideNav() {
$("#mySidenav").hide();
$(".shadow-full").hide();
menuAberto = false;
}
$("#Close_Sidenav").click(fechaSideNav);
$(document).click(function(e) {
if (!menuAberto) return;
var foraMenu = !$(e.target).closest('#mySidenav')[0];
if (foraMenu) fechaSideNav();
})
// Abre Sidenav
$("#Open_Sidenav").click(function(e) {
e.stopPropagation();
$("#mySidenav").toggle(500);
menuAberto = true;
$("body").append('<div class="shadow-full"></div>');
});