First animation in JS | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

First animation in JS

Hi! I just did the lection in the JS course where we see an animation of a box moving to the right within another box. Wanting to experiment a bit more I tried to create an animation so that the box would then move down, and to the left and then up again and then just round and round in "circles". It works fine until it's time to move left (and then up), so I was wondering if someone had any tips for how I can fix this issue?:) I've pasted the JS-code in below and the project can also be found on my profile, thanks for any help!:) /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); var toTheRight = true var down = false var toTheLeft = false var up = false function move() { if(pos >= 150 && toTheRight) { //clearInterval(t); toTheRight = false pos = 0 down = true } if(pos >= 150 && down) { pos = 0 down = false toTheLeft = true } if (pos>=150 && toTheLeft) { pos = 0 toTheLeft= false up=true } if (pos>=150 && up) { pos = 0 up = false toTheRight = true } if (toTheRight) { pos += 1; box.style.left = pos+'px'; } if (down) { pos += 1; box.style.top = pos+'px' } if (toTheLeft) { console.log("Hei") pos += 1; box.style.right = pos + 'px' } if (up) { pos+=1; box.style.bottom = pos + 'px' } } };

12th Jan 2023, 10:51 AM
Henrik Grenersen
Henrik Grenersen - avatar
4 Answers
+ 2
We can't have opposite position both set. Like box.style.left = 0; box.style.right = 0; Or box.style.top: 0; box.style.bottom: 0; But when you start left function, it set left and you have right from before so it don't work. Your code keep cycling right and bottom, if we look long enough. So some style need to be removed completely, best is to use className-s and add and remove this class from element. So you won't change your code much. Also another solution is to type code like me, I set just top and left, and then I used minus values to turn it to another direction: https://code.sololearn.com/WCLmdmWLpLVT/?ref=app If you wanna make even better animation(better performance), check game development course here, or just read this article: https://javascript.info/js-animation
12th Jan 2023, 12:43 PM
PanicS
PanicS - avatar
12th Jan 2023, 12:29 PM
SoloProg
SoloProg - avatar
+ 1
Check this to learn how to add/remove className (class what we can use in css to style): https://www.w3schools.com/howto/howto_js_add_class.asp https://www.w3schools.com/howto/howto_js_remove_class.asp
12th Jan 2023, 12:49 PM
PanicS
PanicS - avatar
+ 1
Thanks to the both of you!! Cool program @soloProg!:)
12th Jan 2023, 5:40 PM
Henrik Grenersen
Henrik Grenersen - avatar