Seeking a solution for my mobile navigation menu that closes when clicking outside the links or on one of them, without using jQuery. How can I achieve this with JavaScript ES6?
Current code snippet:
const navSlide = () => {
const burger = document.querySelector('.burger');
const nav = document.querySelector('.nav-links');
burger.addEventListener('click', () => {
nav.classList.toggle('nav-active');
})
}
navSlide();
html {
scroll-behavior: smooth;
}
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
font-family: Gelion;
background-color: #fa555204;
}
.nav-links li a, .logo {
text-decoration: none;
}
ul {
list-style: none;
}
.main-nav {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 18px;
height: 10%;
padding: 20px 0;
}
.nav-links {
display: flex;
}
.nav-links li {
padding: 0 15px;
}
.burger{
display: none;
}
/* Media Query - Mobile */
@media only screen and (max-width: 700px) {
body {
overflow-x: hidden;
}
/* Burger Menu */
.nav-links {
position: fixed;
right: 0;
height: 100vh;
width: 60%;
top: 0vh;
background-color: var(--secondary-color);
display: flex;
justify-content: space-evenly;
align-items: center;
flex-direction: column;
transform: translateX(100%);
transition: transform 0.5s ease-in;
z-index: 1;
}
.nav-links li a {
color: #fff;
}
.nav-active {
transform: translateX(0%);
}
.main-nav .burger {
display: block;
cursor: pointer;
font-size: 35px;
}
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet"/>
<nav class="main-nav">
<a href="#" class="logo" />Logo</a>
<ul class="nav-links">
<li><a href="#Overview">Overview</a></li>
<li><a href="#Contagion">Contagion</a></li>
<li><a href="#Symptoms">Symptoms</a></li>
<li><a href="#Prevention">Prevention</a></li>
<li><a href="#Contact">Contact</a></li>
</ul>
<div class="burger">
<i class="fas fa-bars"></i>
</div>
</nav>