javascrip for burger menu

Asked

Viewed 53 times

0

Hello, I’m trying to create a hamburger menu and for that I would need to change an element #headercontainer ul as soon as the burger menu was clicked.

I used the Javascript code below

let menuButton = document.querySelector(".menuButton");
let menu = document.querySelector("#headercontainer ul");
menuButton.addEventListener("click", function(){
    menu.classList.toggle("open");
}); 

And I used the HTML below

<header>
    <div id = "headercontainer">
        <div id = "logoheader">

            <img class="logo" src="images/logo.png" " alt="logo">
        </div>
        <div class="menuButton"><a href=“#">☰</a></div> 

        <div id="nav-links" class="menu-top-bar-container">
            <ul id="menu-top-bar" class="menu">
                <li id="menu-item-176" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-home current-menu-item page_item page-item-140 current_page_item menu-item-176"><a href="#" aria-current="page">Home</a></li>
                <li id="menu-item-178" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-178"><a href="#">link2</a></li>
                <li id="menu-item-186" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-186"><a href="#">link3</a></li>
                <li id="menu-item-187" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-187"><a href="#">link4</a></li>
                <li id="menu-item-188" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-188"><a href="#">link5</a></li>
            </ul>
        </div>

    </div>

</header>

Thank you.

1 answer

1

Good as your hamburger is contained in an anchor </a>, you must first cancel the redirect event:

let menuButton = document.querySelector(".menuButton");
let menu = document.querySelector("#nav-links");
menuButton.addEventListener("click", function(e){
    e.preventDefault();
    menu.classList.toggle("open");
});

And for ease css use the class open in the menu container by selecting the #nav-links

Browser other questions tagged

You are not signed in. Login or sign up in order to post.