I want to make an image move with a while loop in javascript but it isn’t working.
This is the javascript code:
var i = 0; while(i != 1000){ document.getElementById("poza").style.left= i; i = i + 20; }
The css code:
#poza{ position: absolute; left: 0px; width: 500px; height: auto; }
And the html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="index.css"> </head> <body> <img id="poza" src="ali_si_david_camp.jpg" alt="ali_si_david_camp"> <script src="index.js"></script> </body> </html>
Advertisement
Answer
You can try this approach as well.
var i = 0; var timer = setInterval(()=>{ document.getElementById("poza").style.left= i+'px'; i = i + 1 if(i > 1000) { clearInterval(timer); } }, 30)
#poza{ position: absolute; left: 0px; width: 500px; height: auto; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="index.css"> </head> <body> <img id="poza" src="https://s.imgur.com/images/logo-1200-630.jpg?2" alt="ali_si_david_camp"> <script src="index.js"></script> </body> </html>