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()">×</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.