Reputation: 1033
I tried to create a slide with 5 images but the javascript is not working
<body onload='slide(0)'>
<div id='slide'>
</div>
</body>
This is the javascript I used;
function slide(i)
{
document.getElementById('slide')
.style.backgroundImage = 'url(../img/' + i + '.jpg)';
setTimeout(slide((i+1)%5), 3000);
}
Upvotes: 0
Views: 59
Reputation: 123739
This is because you are not setting a function reference to the timer, instead just invoking the function slide
and result is set as a callback for the timer which is undefined.
Try:
function slide(i) {
document.getElementById('slide').style.backgroundImage = 'url(../img/' + i + '.jpg)';
setTimeout(function () { //<-- Set the reference here
slide((i + 1) % 5); //Get the mod
}, 3000);
}
Or using function.bind
function slide(i) {
document.getElementById('slide').style.backgroundImage = 'url(../img/' + i + '.jpg)';
setTimeout(slide.bind(this, (++i) % 5), 3000);//<-- Set the function context using bind with the argument as next value of i
}
Upvotes: 2