javascripthtmlcssfrontendvisual-web-developer

Smooth toggle Javascript function


Well what I want to do is to toggle a menu when is clicked but it's not smooth and it feels tough, I'm a newbie in JS but I do know CSS and HTML well enough, so is there a way to smooth this toggle function?

menu unclicked:

menu unclicked

menu clicked:

menu clicked

const toggleButton = document.getElementsByClassName("nav__toggle-button")[0];
const navbarLinks = document.getElementsByClassName("nav__links")[0];

toggleButton.addEventListener("click", () => {
    console.log("clicked");
    navbarLinks.classList.toggle("active");
    toggleButton.classList.toggle("open");
});

Solution

  • If you want to solve this with CSS you can 'animate' the two divs with the transitions property: https://www.w3schools.com/css/css3_transitions.asp

    close state:

    div {
      opacity: 0;
      transition: opacity 1s;
    }
    

    open state:

    div.active {
      opacity: 1;
      transition: opacity 1s;
    }
    

    Two minors:

    1. don't use BEM classes to trigger an event listener, use instead a proper class (js-click or something..)

    2. a small refactor for your first two lines:

    const [toggleButton] = document.querySelectorAll(".nav__toggle-button")
    const [navbarLinks] = document.querySelectorAll(".nav__links")