Question: WHAT THE "myMove()" METHOD DOES? Can you explain it?
#myContainer { width: 400px; height: 400px; position: relative; background: yellow; } #myAnimation { width: 50px; height: 50px; position: absolute; background-color: red; }
Click Me
function myMove() { var elem = document.getElementById("myAnimation"); var pos = 0; var id = setInterval(frame, 10); function frame() { if (pos == 350) { clearInterval(id); } else { pos ; elem.style.top = pos 'px'; elem.style.left = pos 'px'; } } }CodePudding user response:
Quick note: In this answer, I'll be assuming the final question reads:
What does the `myMove()` method do?
Let's first take a look at the variables:
var elem = document.getElementById("myAnimation");
var pos = 0;
var id = setInterval(frame, 10);
The variable elem
refers to the red box which is being moved across the canvas (a div element). We set the pos
tick variable to 0, which will control how many times we will move the box across the screen. Finally, id
refers to a setInterval function which calls the defined frame
function every 10 milliseconds.
Now let's look at the function frame
:
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos ;
elem.style.top = pos 'px';
elem.style.left = pos 'px';
}
}
First, it runs a quick check to see if the ticks are done, or in other words, checks to see if the position is 350. Then, if it is, it stops the loop. If it is not, it makes the box move down 1 pixel by setting the position from the top to the pos
variable.
All of this code is contained within the myMove()
function.