I am currently working on enhancing a menu with a basic functionality. The goal is to toggle the menu between showing and hiding when a button is clicked, managed by a CSS class using JavaScript.
However, I have encountered an issue when attempting to combine this feature with window.addEventListener to close the menu upon an outside click. For some reason, it doesn't seem to work as expected. Can anyone shed light on why this might be happening?
Below is the code snippet that illustrates the structure of the menu setup:
<div class="c-wrapper">
<button type="button" class="c-btn"> Click Me</button>
<ul class="c-navigation">
<li><a href="#">Hi there</a></li>
<li><a href="#">Hello</a></li>
<li><a href="#">Hola</a></li>
<li><a href="#">Konichiwa</a></li>
</ul>
</div>
Your assistance in resolving this matter would be greatly appreciated. Thank you in advance.
.c-wrapper{
position:relative;
}
.c-btn{
background-color:royalblue;
border:none;
color:white;
padding:0.5rem 2rem;
cursor:pointer;
outline:none;
}
.c-navigation{
list-style:none;
background-color:#ccc;
position:absolute;
margin:0;
padding:0;
display:none;
li{
margin-top:0.5rem;
}
a{
text-decoration:none;
color:black;
padding:1.4rem;
}
}
.is-active{
display:block;
}
Lastly, here is the JavaScript code that is causing the issue:
var button = document.querySelector('.c-btn');
button.addEventListener('click', function(){
document.querySelector('.c-navigation').classList.toggle('is-active');
});
window.addEventListener('mouseup', function(event){
var menu = document.querySelector('.c-navigation');
if(event.target != menu && event.target.parentNode != menu){
menu.style.display='none';
}
});