Ghoyos Ghoyos - 4 months ago 7
Javascript Question

Why isn't this transition working?

<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 as far as the box moving left to right. I've used
style.transition
successfully before to move a circle slowly from left to right but this box does not behave the way im trying to get it to. The box should not instantly move from left to right, it should take 4s as stated in the style.transition script. Dont understand what im doing wrong.

Answer

you need to set also a value to start from in your style sheet (all browsers won't assume a 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>

Comments