I wrote the following code for move a box to right and return it to left, and repeat this action forever.
This code works, but is there a better solution?
function move(){ let box = document.getElementById("box"); if(box.style.left.replace("px","") < 180 && check == true){ moveRight(box); }else if (box.style.left.replace("px","") == 180 || check == false) { if(box.style.left.replace("px","") > 0){ check = false; moveleft(box); }else if (box.style.left.replace("px","") == 0){ check = true; } } } function moveRight(box){ if(box.style.left != ""){ let temp = box.style.left.replace("px",""); temp = parseInt(temp); box.style.left = temp+1+"px"; }else{box.style.left = "1px";} } function moveleft(box){ if(box.style.left != ""){ let temp = box.style.left.replace("px",""); temp = parseInt(temp); box.style.left = temp-1+"px"; }else{box.style.left = "1px";} } var check = true; setInterval(move,10);
#plan{ width: 200px; height: 200px; background: #00C0FF; position: relative; } #box{ width: 20px; height: 20px; background: red; position: absolute; }
<!DOCTYPE html> <html> <head> </head> <body> <div id="plan"> <div id="box"></div> </div> </body> </html>