I am trying to do a simple animation in javascript. I'd like to start the animation when pressing the "Click Me" button, to reset it by pressing it again and to restart it by pressing it a third time.
The code I am pasting stops working after resetting the animation. What am I doing wrong?
I tried to add some logs to track my variables but I really can't understand the problem.
var terminateConditionFullfiled;
function ClickManager() {
var elem = document.getElementById("animate");
var pos_top = elem.style.top;
var pos_left = elem.style.left;
if (pos_top != 0 && pos_left != 0) {
elem.style.top = 0 + "px";
elem.style.left = 0 + "px";
terminateConditionFullfiled = true;
WritePosition(elem);
var tt = document.getElementById("tt");
tt.innerHTML = "terminateConditionFullfiled = " + terminateConditionFullfiled;
} else {
terminateConditionFullfiled = false;
myMove();
var tt = document.getElementById("tt");
tt.innerHTML = "terminateConditionFullfiled = " + terminateConditionFullfiled;
}
}
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (terminateConditionFullfiled) {
return;
}
if (pos == 350) {
clearInterval(id);
Back();
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
WritePosition(elem);
}
}
}
function Back() {
var elem = document.getElementById("animate");
var pos = 350;
var id = setInterval(frame, 5);
function frame() {
if (terminateConditionFullfiled) {
return;
}
if (pos == 0) {
clearInterval(id);
myMove();
} else {
pos--;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
WritePosition(elem)
}
}
}
function WritePosition(elem) {
var log = document.getElementById("log");
log.innerHTML = elem.style.top + " " + elem.style.left;
}
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
<p><button onclick="ClickManager()">Click Me</button></p>
<p id="log">Log is here </p>
<p id="tt">terminateConditionFullfiled = </p>
<div id="container">
<div id="animate"></div>
</div>