1
div.addEventListener('click', () => {
        for (let i=1; i<3000; i++) {
          setTimeout(() => {

            let style = div.clientHeight-1;

            style = style + 'px'; 
            div.style.height = style;

          },i)
        }

    })

Why doesn't this code work? I have a div element 500x500 and I try to animate it's height. When I set let style = div.clientHeight - 2; or to a number bigger than 2, it works, but it doesn't work for 1. What is the problem, and how do I animate the height with JS properly?

LearningMath
  • 851
  • 4
  • 15
  • 38

1 Answers1

6

You could do this using minimal Javascript and use CSS instead.

Add a transition: height 3s; to your <div> and create a class that changes the height of your <div>.

After a click on it, just add the class in Javascript:

let div = document.querySelector('div');

div.addEventListener('click', () => {
  div.classList.add('clicked');
})
div{
  border: 1px solid black;
  height:100px;
  transition: height 3s;
}

div.clicked{
  height: 3000px;
}
<div></div>
Zenoo
  • 12,670
  • 4
  • 45
  • 69