简体   繁体   中英

How to close the menu when clicking outside the div with pure javascript?

I managed to make the function to open the menu when clicking on the button, but I'm having some difficulty closing the menu when clicking outside it, I looked for something about it before coming here, so I ask for everyone's understanding.

By clicking on the menu

在此处输入图像描述

It opens normally

在此处输入图像描述

I'm trying to create a function so that when the user clicks outside the div, the menu closes by itself

This is my menu's html code

<div id="main-menu-btn" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
<a href="<?= base_url() ?>user/home">Home</a>
<a href="<?= base_url() ?>user/meus_imoveis">Meus imóveis</a>
<a href="<?= base_url() ?>user/meus_clientes">Meus clientes</a>
<hr>
<a href="<?= base_url() ?>user/profile">Meu perfil</a>
<a href="<?= base_url() ?>user/users">Meus usuários</a>
<a href="<?= base_url() ?>user/faturas">Minhas faturas</a>
<hr>
<a href="#" data-toggle="modal" data-target="#modalMaterial">Materiais</a>
<a href="#" data-toggle="modal" data-target="#modalSupport">Suporte</a>
<hr>
<a href="<?= base_url('auth/logout'); ?>">Sair</a>

And this is my javascript code

function openNav() {
  document.getElementById("main-menu-btn").style.width = "250px";
}

function closeNav() {
  document.getElementById("main-home").style.width = "0";
}

please add below javascript code

 const box = document.querySelector(".sidenav")
// Detect all clicks on the document
document.addEventListener("click", function(event) {
  // If user clicks inside the element, do nothing
  if (event.target.closest(".sidenav")) return
  // If user clicks outside the element, hide it!
   document.getElementById("main-menu-btn").style.width = "0";
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM