I’m practicing using javascript to animate css. I copied some source code from w3schools that makes a rectangle (the animate div) travel diagonally right across a larger rectangle (container div).
Here’s that original code:
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id ="container">
<div id ="animate"></div>
</div>
<script>
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
</script>
</body>
</html>
I wanted the rectangle to travel in reverse when it got to the bottom right corner of the container div. Here’s how I tried to do it:
<!Doctype html>
<html>
<title>
</title>
<head>
</head>
<style>
#container
{
width: 400px;
height: 400px;
position: relative;
background: blue;
}
#animate
{
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body onload = "myMove()">
<div id ="container">
<div id ="animate">
</div>
</div>
<script>
function myMove()
{
var elem = document.getElementById("animate");
var posTop = 0;
var posLeft = 0;
var id = setInterval(frame, 5);
function frame()
{
posTop++;
posLeft++;
if(posTop === 350)
{
while(posTop > 0)
{
posTop--;
}
}
if(posLeft === 350)
{
while(posLeft > 0)
{
posLeft--;
}
}
elem.style.top = posTop + 'px';
elem.style.left = posLeft + 'px';
}
}
</script>
</body>
</html>
For some reason it just restarts the original animation. I notice that this may have something to do with how the setInterval() function works, but I’m not sure.