I want to toggle a navbar on click using a button and if the navbar is already active I want to disable it when the user clicks anywhere. The event listeners are all connected and the toggling code works normally but implementing the "click anywhere on the screen to turn off" feature isn't working.
Edit: I can now toggle by clicking anywhere but I can't toggle using the button I can only turn it on and not off.
const button = document.querySelector('button.mobile-menu-button');
const menu = document.querySelector('.mobile-menu');
let menuActive = false;
button.addEventListener('click', (e) => {
e.stopPropagation();
if (!menuActive) {
menu.classList.toggle('hidden');
menuActive = true;
}
});
window.addEventListener('click', () => {
if (menuActive) {
menu.classList.toggle('hidden');
menuActive = false;
}
});
CodePudding user response:
The problem is that when you click on the button, you are also clicking on the window at the same time. You should use stopProgopation()
.
Here is a solution. When the button is clicked, the menu gets shown. If the user then clicks on the screen somewhere else other than the button, the menu will disappear.
<div id="menu" >This is the menu</div>
<button >Button</button>
<script>
const button = document.querySelector('button.mobile-menu-button');
const menu = document.getElementById('menu');
let menuActive = false;
button.addEventListener('click', (e) => {
e.stopPropagation();
if (!menuActive) {
menu.classList.toggle('hidden');
menuActive = true;
}
});
window.addEventListener('click', () => {
if (menuActive) {
menu.classList.toggle('hidden');
menuActive = false;
}
});
</script>
<style>
.mobile-menu {
display: block;
}
.hidden {
display: none;
}
</style>
CodePudding user response:
I found I didn't need a condition for the button itself, only the window. Thanks to everyone for helping.
const button = document.querySelector('button.mobile-menu-button');
const menu = document.querySelector('.mobile-menu');
let menuActive = false;
button.addEventListener('click', (e) => {
e.stopPropagation()
menu.classList.toggle('hidden');
menuActive = true;
});
window.addEventListener('click', () => {
if (menuActive) {
menu.classList.toggle('hidden');
menuActive = false;
}
});