+ 2
How to move squre to another side?
How to move squage from one side to other? https://code.sololearn.com/953/#js here go to left, but what should i make to go back?
4 Respostas
+ 17
@Burey it will be of great help if you could explain the workings inside the if and else statement of the move() function.
+ 15
@Burey,thank you very much.
+ 8
//calling the function in window.onload to make sure the HTML is loaded
window.onload = function() {
var pos = 0;
//our box element
var box = document.getElementById('box');
var t = setInterval(move, 10);
var dir = 1;// direction
function move() {
if((pos > 150 && dir ===1) || (pos < 0 && dir === -1)) {
dir*=-1; // switch direction
}
else {
pos += 1*dir;
box.style.left = pos+'px';
}
}
};
+ 7
notice that i added a dir variable which represent the direction of movement (1 move right, -1 move left)
<-----------A---------> <-----------B--------->
if((pos>150 && dir ==1)||(pos<0 && dir== -1))
A: if the current position has passed the right border at position 150 AND also the direction of movement is to the right ---> switch direction of movement
B: if the current position has passed the left border at position 0 AND also the direction of movement is to the left ---> switch direction of movement
inside the else statement:
pos += 1*dir; <--- this update the variable which represents the position of the box
box.style.left = pos+'px'; <--- this applies the new location to the box