0

Hello all
I want to create an animation for a dropdown using css and javascript. But when the display is set to none, the animations don't work maybe because display property can't be animated. But if I delay the display property, it gives animation enough time to load. So is there any possible method to delay the same display property through callback function? Here is my code:

function myfun() {
  let dis = document.getElementsByClassName("litems")[0];
  if (dis.style.display == "none") {
    dis.style.display = "block";
    dis.style.animation = "up 2s ease-in 1"
  } else {
    dis.style.animation = "down 2s ease-in 1";
    setTimeout(() => {
      dis.style.display = "none";
    }, 2000)
  }
}
.list ul {
  background: orchid;
  position: absolute;
  display: block;
}

@keyframes up {
  0% {
    top: 0px;
    background: white;
  }
  100% {
    top: 400px;
    background: orange;
  }
}

@keyframes down {
  0% {
    top: 400px;
    background: orange;
  }
  100% {
    top: 0px;
    background: white;
  }
}
  <button onclick="myfun()">Click it to toggle</button>
  <div class="list">
    <ul class="litems">
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
      <li>Item 4</li>
    </ul>
  </div>
</body>

Thank you very much.

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
Apurv
  • 1
  • 1
  • 1
    Sorry, it's hard to tell what you're asking for. Are you trying to find out when an animation finishes so you can avoid the `setTimeout` in your code? For that, you would use the [transitionend event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/transitionend_event) . This [answer](https://stackoverflow.com/questions/29017379/how-to-make-fadeout-effect-with-pure-javascript/29017547#29017547) may be useful – Ruan Mendes Jun 13 '22 at 19:18
  • I'm looking for a callback function which can do the same thing as the setTimeout here i.e display property is set to none only after the animation gets loaded completely. – Apurv Jun 14 '22 at 12:00
  • In that case, the question is a duplicate of [Is there a callback on completion of a CSS3 animation?](https://stackoverflow.com/q/6186454/1048572) – Bergi Jun 14 '22 at 12:18
  • @Apurv That is what the `transitionend` or in your case, the [`animationend` event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/animationend_event) is for. Why did that not work for you? – Ruan Mendes Jun 14 '22 at 13:02

0 Answers0