Home > Software engineering >  Smooth toggle Javascript function
Smooth toggle Javascript function

Time:02-26

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");
});

CodePudding user response:

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")

CodePudding user response:

The javascript is correct, what you need is css animations, fade in fade out or slide in slide out, i suggest you take a look at this: https://animate.style/

CodePudding user response:

You can apply transition and transform properties to the element through CSS. For example, if you are using a drop down menu and controlling the slide and the opacity:

transform: translateY(-10px);
transition: opacity 150ms ease-in-out, transform 150ms ease-in-out;

You could check out: https://developer.mozilla.org/en-US/docs/Web/CSS/transition

CodePudding user response:

All you need is a transition and transform property that you can toggle. Transform CSS property is used for handling dimensions, orientation etc of a DOM element. Adding transition adds an effect where the transform properties if changed, change gradually.

const closeButton = document.getElementById("close")

closeButton.addEventListener("click", () => {
  const menu = document.getElementById("nav-links")

  menu.classList.toggle("closed-list");
})
ol {
  width: 100%;
  list-style-type: none;
  background: gray;
  transition: all 0.4s ease-in-out;
}

.closed-list {
  transform: scaleY(0);
  transform-origin: top;
}

li {
  text-align: center;
  padding: 12px 0px;
  color: white;
  font-weight: 700;
  font-size: 18px;
}

#close-container {
  text-align: right;
}
<div>
  <div id="close-container">
    <button id="close">
      open/close
    </button>
  </div>
  <ol id="nav-links">
    <li>Test 1</li>
    <li>Test 2</li>
    <li>Test 3</li>
    <li>Test 4</li>
  </ol>
</div>

  • Related