javascript – identify a click outside the div with jquery


Well I know how to identify a click in Cida of an element. I do like this:

// Fecha Sidenav
$("#Close_Sidenav").click(function() {

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


You can add an event window to window or document and at the time of click check if 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() {
    menuAberto = false;

$(document).click(function(e) {
    if (!menuAberto) return;
    var foraMenu = !$('#mySidenav')[0];
    if (foraMenu) fechaSideNav();

// Abre Sidenav
$("#Open_Sidenav").click(function(e) {
    menuAberto = true;
    $("body").append('<div class="shadow-full"></div>');


Scroll to Top