简体   繁体   中英

Burger menu doesn't disappear after clicking JS

I'm doing a burger menu for the responsiv. I use a classic JS function onclick to show the responsive burger menu. It's work but when I click on the menu, the menu doesn't disappear.

 function myFunction() { const button = document.getElementById("menuBurgerFunction"); const y = document.getElementById("SecondNav"); button.classList.toggle("change"); if (y.style.display === "") { y.style.display = "block"; } else { y.style.display = ""; } }
 <div id="boutonBurger"> <div class="burger" id="menuBurgerFunction" onclick="myFunction(event)"> <div class="bar1"></div> <div class="bar2"></div> <div class="bar3"></div> </div> </div> </div> <nav id="SecondNav"> <ul id="TargetNav"> <li><a href="#itineraires">Itinéraires</a></li> <li><a href="#infoTrafic">Infos trafic</a></li> <li><a href="#actualite">Actualité</a></li> <li><a href="#contact">Contact</a></li> </ul> </nav>

Do I need to use event or listener? Maybe there is an easiest way? Thx

Is there an easier way than changing the display style of the menu in an if-else block?

Yes, there's a slightly easier way: create a hidden class and toggle it on the menu.

CSS:

.hidden {
  display: none'
}

JavaScript:

const y = document.getElementById("SecondNav");
y.classList.toggle('hidden');

I have added show and hide classes and toggling it using those classes. Yes we can make use of the attributes as well

 function myFunction(e) { const button = document.getElementById("menuBurgerFunction"); const y = document.getElementById("SecondNav"); button.classList.toggle("change"); if (y.classList.contains('show')) { y.classList.remove('show'); y.classList.add('hide'); } else { y.classList.remove('hide'); y.classList.add('show'); } }
 .show { display: block; }.hide { display: none; }
 <div id="boutonBurger"> <div class="burger" id="menuBurgerFunction" onclick="myFunction(event)"> <div class="bar1">icon</div> <div class="bar2"></div> <div class="bar3"></div> </div> </div> </div> <nav id="SecondNav" class="show"> <ul id="TargetNav"> <li><a href="#itineraires">Itinéraires</a></li> <li><a href="#infoTrafic">Infos trafic</a></li> <li><a href="#actualite">Actualité</a></li> <li><a href="#contact">Contact</a></li> </ul> </nav>

In fact, if I give another class to the burger menu, that's disrupt the onclick function and the secondNav never appear. My HTML/CSS and the function are good, I think I just need another function. This one should do if burger menu is show && if the menubar changed onclick()navbar style.display="none";

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