+ 2

How to make box move right and left endlessly?

When clear interval is set it just doesn't work anymore.. how can I stop it from running the animation to the right and then go to left and so on endlessly? //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); function move() { if(pos >= 150 ) { var y = setInterval(moveLeft, 10); clearInterval(t); } else { pos +=1; box.style.left = pos+'px'; } } function moveLeft() { pos--; box.style.right = pos+'px'; } }; https://code.sololearn.com/953/#js

11th Feb 2018, 6:28 PM
GMMs
GMMs - avatar
3 Antworten
+ 1
What I would do is set two different functions to move the box in either direction, kind of like what you already have except with a function to move the box right. Then, you could set a similar if statement that checks if the position is less than or equal to 0, making it run the function that moves the box right at a set interval until its position is greater than or equal to 150.
11th Feb 2018, 6:32 PM
Faisal
Faisal - avatar
0
do this I think it will work window.onload = function(){ var pos = 0; var box = document.getElementById('absolute'); var t = setInterval(move, 10); function move(){ if (pos >= 150){ setInterval(moveLeft, 10); //clearInterval(t); } else{ pos += 1; box.style.left = pos + 'px'; } } function moveLeft(){ if(pos < 0){ setInterval(move, 10); } else{ pos -= 1; box.style.right = pos + 'px'; } } };
21st Apr 2023, 9:44 AM
VOLCY Wanly
VOLCY Wanly - avatar
0
---- html and css code for the box code of the javascript (do this I think it will work)---- html code: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="-width, initial-scale=1" /> <link rel="stylesheet" href="main.css"> <title>Box Move</title> </head> <body> <div id="relative"> <div id="absolute"> </div> </div> <script src="main.js" defer></script> </body> <html> css: #relative{ width: 200px; height: 200px; background-color: green; position: relative; } #absolute{ width: 50px; height: 50px; background-color: red; position: absolute; }
21st Apr 2023, 9:48 AM
VOLCY Wanly
VOLCY Wanly - avatar