animate div height one after the other onload javascript

守給你的承諾、 提交于 2019-12-04 17:40:42

You can use transitionend event of the first box, to start transition of box2:

window.onload = function () {
  const box = document.getElementById('box');

  box.addEventListener("transitionend", () => {
    document.getElementById('box2').style.height = "100vh";
  }, {once: true});

  box.style.height = "100vh";
}

In case you want to start 2nd animation before 1st one finished you could use setTimeout function with desired delay:

window.onload = function () {
  const box = document.getElementById('box');

  setTimeout(() => {
    document.getElementById('box2').style.height = "100vh";
  }, 200);

  box.style.height = "100vh";
}

Try this..

window.onload = function () {
  var box = document.getElementsByClassName("box");
  for(var i = 0; i < box.length; i++)
  {
     box[i].style.height = "100vh";
  }
} 

There you have it. A code to animate each of your boxes one after the other.

Notice I had to convert your node list to an array first and then reverse the array. This is in order to be able to pop elements from the array and use the lenght of the array to terminate the recursive function animateBoxes().

I used the setTimeout() function to execute the recursive function 1 second at a time. You can modify the time parameter to your need.

The major advantage of this method is that it can automatically animate any number of boxes.

window.onload = function () { 
    let boxes = [].slice.call(document.querySelectorAll(".box")).reverse();
    animateBoxes(boxes);

    function animateBoxes(boxes) {
        if(boxes.length) {
            setTimeout(function() {
                boxes.pop().style.height = "100vh";
                animateBoxes(boxes);
            }, 1000);
        }
    }
}
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.container {
    width: 100%;
    height: 100vh;
    background: green;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
}

#box, #box2, #box3, #box4 {
    width: 100%;
    height: 0;
    position: relative;
    top: 0;
    transition: 1s;
}

#box {
    background: red;
}

#box2 {
    background: purple;
}

#box3 {
    background: orange;
}

#box4 {
    background: yellow;
}
<div class="container" id="container"> 
    <div class="box" id="box"> box1 </div> 
    <div class="box" id="box2"> box2 </div> 
    <div class="box" id="box3"> box3 </div> 
    <div class="box" id="box4"> box4 </div> 
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!