Javascript animation box | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Javascript animation box

Help me to get rid of the error please! Every time I get this error at the last line- 'style property cannot be null.' Here is my code: <!DOCTYPE html> <html> <head> <title>Animation-Box</title> </head> <body> <div id="container"></div> <div id="box"></div> </body> </html> #container{ width:300px; height:300px; background-color:#44DD55; position:relative; } #box{ width:30px; height:30px; background-color:#FFFFFF; position:absolute; } var pos = 0; var box = document.getElementById("box"); var t = setInterval(move, 20); function move() { if (pos >= 270) { clearInterval(t); } else { pos += 1; box.style.left = pos + "px"; } }

20th Feb 2021, 12:56 AM
Imtiaz Faisal
Imtiaz Faisal - avatar
4 Answers
+ 4
Add border to #box to make the movement more observable. And wrap the code in JS tab in a load event handler function. The script is running before the DOM is completely built, that's why it failed. https://www.sololearn.com/post/90825/?ref=app window.onload = function() { var pos = 0; var box = document.getElementById("box"); var t = setInterval(move, 20); function move() { if (pos > 270) { clearInterval(t); } else { pos += 1; box.style.left = pos + "px"; } } }
20th Feb 2021, 1:39 AM
Ipang
+ 4
Most welcome 👌
20th Feb 2021, 1:49 AM
Ipang
+ 2
Thank you Ipang!
20th Feb 2021, 1:48 AM
Imtiaz Faisal
Imtiaz Faisal - avatar
20th Feb 2021, 3:59 AM
SAN
SAN - avatar