Why does this transition not work?

<html> <head> <title>Singularity</title> <style> body { background-color: grey; } #boxOne { position:relative; height:150px; width:150px; background-color: black; } </style> <script> function playOne(){ document.getElementById("boxOne").style.left = "30px"; document.getElementById("boxOne").style.transition = "all 4s"; } </script> </head> <body> <div id="boxOne" onclick="playOne()"></div> </body> </html> 

The above code works the same as a field moving left to right. I used style.transition successfully to move the circle slowly from left to right, but this field does not behave the way I'm trying to get it. The box should not instantly move from left to right, it should take 4 seconds, as indicated in the style.transition script. I donโ€™t understand what I am doing wrong.

+5
source share
2 answers

you also need to set the value to start in your stylesheet (all browsers will not accept the default value)

 function playOne() { document.getElementById("boxOne").style.left = "30px"; document.getElementById("boxOne").style.transition = "all 4s"; //might be coherent to declare this at first //or even straight in the style sheet } 
 body { background-color: grey; } #boxOne { position: relative; height: 150px; width: 150px; left: 0; /* added this, so calculation can be done from an earlier css value*/ background-color: black; } 
 <div id="boxOne" onclick="playOne()"></div> 
+5
source

You need to set the initial value on the left so that it works fine

  <head> <title>Singularity</title> <style> body { background-color: grey; } #boxOne { position:relative; height:150px; width:150px; background-color: black; left:0px; /*value left added*/ } </style> <script> function playOne(){ document.getElementById("boxOne").style.left = "250px"; document.getElementById("boxOne").style.transition = "all 4s"; } </script> </head> <body> <div id="boxOne" onclick="playOne()"></div> </body> </html> 
+1
source

All Articles