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
3 Réponses
+ 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
0
Why tag your code url?
How to open it?
0
Thanks visph. Now it works.