Search code examples
javascriptdrop-down-menuhamburger-menu

menu doesn't hide on second click


I'm facing a problem with a hamburger menu... When I click on the hamburger icon there is no problem, it opens and closes without any problem, also when I click on a link I am well redirected to the sections and the menu closes, no problem so far.

But when i re open the menu and click a second time on a link section, my menu no longer wants to close and I can't figure it out why because i've put a condition, it must have a problem somewhere.. So please if you could help me to understand. Thank you very much. Here is my code :

html :

<header id="home" class="background-color">
<div id="logo">
        <a href="index.php#home"><img src="./img/logo.svg" alt="logo"></a>
    </div>
    <nav id="menu-dekstop">
        <a href="index.php#home">Accueil</a>
        <a href="index.php#projects">Projets</a>
        <a href="index.php#contact">Contact</a>
    </nav>
    <div class="show-menu">
        <div id="logo">
            <a href="index.php#home"><img src="./img/logo.svg" alt="logo"></a>
        </div>
    </div>
    <div id="menu-wrap">
        <nav class="menu">
            <a href="index.php#home">Accueil</a>
            <a href="index.php#projects">Projets</a>
            <a href="index.php#contact">Contact</a>
        </nav>
    </div>
    <div id ="menu-holder" class="menu-holder">
        <button id="open-menu" class="white">
            <div class="burger">
                <span></span>
            </div>
        </button>
    </div>
</header>

JavaScript

burger.addEventListener('click', menuOpen)

function menuOpen()
{
    if (showMenu.style.display == 'block')
    {
        burger.classList.toggle('active');
        menuWrap.style.display = 'none';
        showMenu.style.display = 'none';
    }
    else 
    {
        burger.classList.toggle('active');
        menuWrap.style.display = 'block';
        showMenu.style.display = 'block';
    }
}


Solution

  • There appears to be no listener that closes the menu upon a link click.

    This code will accomplish a menu hide upon link click in the header:

    const header = document.getElementById('home');
    header.addEventListener('click', function (evt) {
      const clickTarget = evt.target;
      if (clickTarget.tagName !== 'A") { return; }
      burger.classList.remove('active);
      menuWrap.style.display = 'none';
      showMenu.style.display = 'none';
    });
    

    Why did the menu get hidden the first time a link was clicked? Not sure, but I suspect it's because the first link click caused a page reload.