Javascript animation box | Sololearn: Learn to code for FREE!

+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"; } }

2/20/2021 12:56:46 AM

Imtiaz Faisal

4 Answers

New Answer

+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"; } } }

+4

Most welcome 👌

+2

Thank you Ipang!

0

Simple js animation https://code.sololearn.com/WfGvyMpF4cVU/?ref=app