How can I hide my hamburger menu when any of the #links (same page links) are clicked or when someone clicks outside the menu area? I believe I need to modify my JS script, but I'm not sure which part needs changing. I am completely new to JavaScript.
const menuBtn = document.querySelector('.menu-btn');
let menuOpen = false;
menuBtn.addEventListener('click', () => {
if (!menuOpen) {
menuBtn.classList.add('open');
document.getElementById("mymobilemenu").style.display = "block";
menuOpen = true;
} else {
menuBtn.classList.remove('open');
document.getElementById("mymobilemenu").style.display = "none";
menuOpen = false;
}
});
.menu-btn {
position: relative;
float: right;
display: flex;
justify-content: center;
align-items: center;
width: 80px;
height: 80px;
cursor: pointer;
transition: all .5s ease-in-out;
border: 3px solid blueviolet;
background: pink;
}
.menu-btn-burger {
width: 50px;
height: 6px;
background: yellow;
border-radius: 5px;
transition: all .5s ease-in-out;
}
.menu-btn-burger::before,
.menu-btn-burger::after {
content: '';
position: absolute;
width: 50px;
height: 6px;
background: grey;
border-radius: 5px;
transition: all .5s ease-in-out;
}
.menu-btn-burger::before {
transform: translateY(-16px);
}
.menu-btn-burger::after {
transform: translateY(16px);
}
/* animation of burger */
.menu-btn.open .menu-btn-burger {
transform: translateX(-50px);
background: transparent;
box-shadow: none;
}
.menu-btn.open .menu-btn-burger::before {
transform: rotate(45deg) translate(35px, -35px);
}
.menu-btn.open .menu-btn-burger::after {
transform: rotate(-45deg) translate(35px, 35px);
}
#mymobilemenu {
display: none;
}
<div class="menu-btn">
<div class="menu-btn-burger">
</div>
</div>
<div id="mymobilemenu">
<li><a href="#section1">section1</a></li>
<li><a href="#section2">section2</a></li>
<li><a href="#section3">section3</a></li>
<li><a href="#section4">section4</a></li>
</div>
<a id="section1">SECTION 1</a>
<p>Here is some dummy text for section 1.</p>
<a id="section2">SECTION 2</a>
<p>More dummy text for section 2.</p>
<a id="section3">SECTION 3</a>
<p>Additional dummy text for section 3.</p>
<a id="section4">SECTION 4</a>
<p>Extra dummy text for section 4.</p>