简体   繁体   中英

Toggle nav menu when clicked on nav links or outside

I have been trying to make my mobile navigation menu to toggle back when I click outside the navigation links or when I click on one of them. I have looked around and I only find jQuery example which I'm avoiding. I want to have an example with JavaScript ES6. So, how can I make it work?

Here is my code:

 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>

you can use css very easy for this Using:focus Selector checkout this link: https://www.w3schools.com/cssref/sel_focus.asp

or try this

.classname:focus{
  //your code here will run while client focused in this class
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM