0

Please help to find error. Why only one circle move in this code JS

Hi. Please help to find the problem. I try to write code when both circle moves Thanks

14th Jun 2017, 5:55 PM
Alex Ihnatsiuk
Alex Ihnatsiuk - avatar
3 Respostas
+ 4
Because you overwrite the window.onload attribute... To set many event listener, you'll need to use the .addEventListener() method: window.addEventListener('load',function () { var pos =0; var box = document.getElementById('circle'); var t = setInterval(move, 10); function move() { if (pos>=400) { clearInterval (t); } else { pos += 1; circle.style.left= pos +'px'; } } }); window.addEventListener('load',function () { var pos1 = 0; var box1 = document.getElementById('circle1'); var t1 = setInterval(move, 500); function move() { if (pos1>=450) { clearInterval (t1); } else { pos1 += 1; circle1.style.left= pos1 +'px'; } } }); ... Anyway, your code work as this, but because you are lucky ^^ When you modify the style.left attribute of your objects, you are refering to auto created variable in global scope for each element having an id value: circle.style.left = ... is supposed to be write: box.style.left = ... as it's the variable name inside wich you have stored the reference of the object with id 'circle' (bar box=document.getElementById('circle')), and by the same wayn with 'circle1' and box1 :P
14th Jun 2017, 6:14 PM
visph
visph - avatar
0
Why tag your code url? How to open it?
14th Jun 2017, 6:03 PM
Calviղ
Calviղ - avatar
0
Thanks visph. Now it works.
14th Jun 2017, 6:49 PM
Alex Ihnatsiuk
Alex Ihnatsiuk - avatar