identify a click outside the div with jquery

3

Well I know how to identify a click on an element. I do this:

// Fecha Sidenav
$("#Close_Sidenav").click(function() {
    $("#mySidenav").hide();
});

But I need $("#mySidenav").hide() to run when I click on the Close_Sidenav element and when I click outside the mySidenav element.

How do I do this?

For more information I'm trying to make this menu close when I click outside it. Menu

    
asked by anonymous 17.12.2016 / 11:04

1 answer

2

You can add an event handset to window or document and at the time of the click check that 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>');
});

jsFiddle: link

    
17.12.2016 / 11:20