+ 3

How can i make this object move more than ones?

<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <img src=" https://ichef.bbci.co.uk/images/ic/480x270/p05394v7.jpg " width="100" height="100" id="YourObject" style="position:relative;" > <br /> <button onclick="move();">Move</button> </body> </html> //js function move() { var obj = document.getElementById("YourObject"); obj.style.left = 50 + 'px'; }

23rd Aug 2017, 12:44 AM
Reward
Reward - avatar
6 Respostas
+ 2
Try change the code to var left = Number(obj.style.left.replace('px','')); obj.style.left = (left + 50) + 'px';
23rd Aug 2017, 1:19 AM
Calviղ
Calviղ - avatar
+ 2
Make THIS your js: var left = 0; setInterval(function(){ var obj = document.getElementById("yourObject"); obj.style.left = left + "%"; left = (left >= 100)? 0: left+=5; }, 50);
23rd Aug 2017, 1:56 AM
Leigh E. O.
Leigh E. O. - avatar
+ 1
instead of using the number 50 you could use a variable that goes up everytime you press the button
23rd Aug 2017, 1:11 AM
Enzo
Enzo - avatar
+ 1
thanks a lot @Calvin but can you help explain more on this line of code? Number(obj.style.left.replace('px',''));
23rd Aug 2017, 1:32 AM
Reward
Reward - avatar
+ 1
the solution of Calvin is perfect +1
23rd Aug 2017, 1:33 AM
MBZH31
MBZH31 - avatar
0
you get the obj.style.left value in the var left without px and cast it in Number. if obj.style.left = 100px then left = 100 so, after you can add 50 to left value to move your img
23rd Aug 2017, 1:37 AM
MBZH31
MBZH31 - avatar