Felipe
Felipe

Reputation: 413

How to close mobile menu when click on hamburger icon using Javascript

I have created a mobile menu that is opening fine when I click on the "hamburger" icon. (Not an image, created with divs and css). I am having some trouble figuring out how to close the mobile menu when a user clicks on the "hamburger" icon. Any tips would be greatly appreciated!

const hamburgerBtn = document.getElementById("hamburger");
const navLink = document.querySelector(".nav__links");

navLink.style.left = "-100%";
hamburgerBtn.addEventListener("click", () => {
  if ((navLink.style.left = "-100%")) {
    navLink.style.left = "0%";
  }
});

Code above is how I am able to make the mobile menu appear.

Upvotes: 1

Views: 685

Answers (2)

Real Quick
Real Quick

Reputation: 2800

Use a ternary operator to check the left style.

Basically,

condition ? true case : false case

const hamburgerBtn = document.getElementById("hamburger");
const navLink = document.querySelector(".nav__links");

navLink.style.left = "-100%";
hamburgerBtn.addEventListener("click", () => {
  navLink.style.left =  navLink.style.left ==="-100%" ? "0" : "-100%";
});
.nav__links {
  position: absolute;
  background: red;
  color: white;
}
<button id="hamburger">NAV</button>
<div class="nav__links">
  HEY
</div>

.

Upvotes: 2

crg
crg

Reputation: 4557

After your if add an else to make it back to the -100% position

const hamburgerBtn = document.getElementById("hamburger");
const navLink = document.querySelector(".nav__links");

navLink.style.left = "-100%";
hamburgerBtn.addEventListener("click", () => {

      if ((navLink.style.left == "-100%")) {
        navLink.style.left = "0%";
      } else {
        navLink.style.left = "-100%";
       }

});

Upvotes: 2

Related Questions