简体   繁体   中英

Event listener only works once

I'm creating this function inside an Event listener to add/remove some classes to my HTML on click. The problem is the Event listener only working for one time and it require to refresh the page to work again. I also tried to use onClick and it doesn't work.

 const menuBtn = document.querySelector('.menu-btn'); const menu = document.querySelector('.menu'); const menuNav = document.querySelector('.menu-nav'); const menuBranding = document.querySelector('.menu-branding'); const navItems = document.querySelectorAll('.nav-item'); let showMenu = false; menuBtn.addEventListener('click', toggleMenu); function toggleMenu() { 'use strict'; if (!showMenu) { menuBtn.classList.add('close'); menu.classList.add('show'); menuNav.classList.add('show'); menuBranding.classList.add('show'); navItems.forEach(item => item.classList.add('show')); // Set Menu State showMenu = true; } else { menuBtn.classList.remove('close'); menu.classList.remove('show'); menuNav.classList.remove('show'); menuBranding.classList.remove('show'); navItems.forEach(item => item.classList.remove('show')); } } 
 <header> <div class="menu-btn"> <div class="btn-line"></div> <div class="btn-line"></div> <div class="btn-line"></div> </div> <nav class="menu"> <div class="menu-branding"> <div class="portrait"></div> </div> <ul class="menu-nav"> <li class="nav-item"> <a href="/" class="nav-link">Home</a> </li> <li class="nav-item"> <a href="/about.html" class="nav-link">About Me</a> </li> <li class="nav-item"> <a href="/work.html" class="nav-link">My Work</a> </li> <li class="nav-item"> <a href="/contact.html" class="nav-link">Contact me</a> </li> </ul> </nav> </header> 

You need to toggle showMenu back to false when you close the menu.

function toggleMenu() {
  'use strict';
  if (!showMenu) {
    menuBtn.classList.add('close');
    menu.classList.add('show');
    menuNav.classList.add('show');
    menuBranding.classList.add('show');
    navItems.forEach(item => item.classList.add('show'));

    // Set Menu State

    showMenu = true;

  } else {
    menuBtn.classList.remove('close');
    menu.classList.remove('show');
    menuNav.classList.remove('show');
    menuBranding.classList.remove('show');
    navItems.forEach(item => item.classList.remove('show'));

    showMenu = false;
  }
}

DEMO

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