CSS transition doesn't work when javascript added properties continuous

Below is a simplified version of a problem I am having with my website.

function move(){
  document.getElementById("box").style.transition = "0s";
  document.getElementById("box").style.top = "100px";
  document.getElementById("box").style.transition = "2s";
  document.getElementById("box").style.top = "0px";
}
#box{
  width:100px;
  height:100px;
  background:red;
  position:relative;
  top:0px;
}
<div id="box" onclick="move()"></div>

What I want it to do is make the box instantaneously jump downwards, and then slowly move back to its starting position. I have tested each of the four lines of code inside move() separately and they work perfect. I just can't get them to run in one go.

What am I doing wrong?

Upvotes: 3

Views: 1700

Answers (2)

Piotr Wicijowski
Piotr Wicijowski

Reputation: 2115

Instead of relying on transitions, it would be better to use @keyframes and animation, so that you don't have to use dirty tricks like changing the transition duration from 0 to actual value mid-animation to achieve the jump. Below is an example that utilizes the @keyframes css features:

function move(){
  document.getElementById("box").style.animation = "movement 2s";
}
#box{
  width:100px;
  height:100px;
  background:red;
  position:relative;
  top:0px;
}
@keyframes movement {
    from {top: 100px;}
    to {top: 0px;}
}
<div id="box" onclick="move()"></div>

Upvotes: 3

Mohammad
Mohammad

Reputation: 21489

It seem the code needs to delay before assigning new property that cause browser can process the request. So you need to use setTimeout() to solving this problem.

function move(){
  document.getElementById("box").style.transition = "0s";
  document.getElementById("box").style.top = "100px";
  setTimeout(function(){
    document.getElementById("box").style.transition = "2s";
    document.getElementById("box").style.top = "0px";
  }, 10);
}
#box{
  width:100px;
  height:100px;
  background:red;
  position:relative;
  top:0px;
}
<div id="box" onclick="move()"></div>

Upvotes: 5

Related Questions