identify a click outside the div with jquery

Asked

Viewed 550 times

3

Well I know how to identify a click on Cida of an element. I do so:

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

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

How do I do it?

For more information I’m trying to get this menu to close when I click off it. Menu

1 answer

2


You can add an event headphone to window or document and at the moment of the click check if the 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: https://jsfiddle.net/fdm4j2k2/

  • 1

    Thank you so much That’s what I wanted

Browser other questions tagged

You are not signed in. Login or sign up in order to post.