Reputation: 25
below is the javascript that I am currently experimenting with. I am teaching myself JS. As things stand this code begins with white space instead of the first image. I wanted to ask somebody if the bgcur=0 would give me a background image at the beginning, instead of white space until the first image loads, which is what currently happens.
If not could somebody show me how to build a preloader for these images?
<script type="text/javascript">
var bgArr = [
'images/bg1.jpg',
'images/bg2.jpg',
'images/bg3.jpg',
'images/bg4.jpg',
'images/bg5.jpg',
'images/bg6.jpg',
'images/bg7.jpg',
'images/bg8.jpg',
'images/bg9.jpg',
'images/bg10.jpg'];
document.body.style.backgroundImage = 'url(' + bgArr[10] + ')';
bgCur = 0;
backgroundSwitch = function () {
if (bgCur == bgArr.length) bgCur = 0;
document.body.style.backgroundImage = 'url(' + bgArr[bgCur++] + ')';
}
window.setInterval(backgroundSwitch, 6000); // Switch every 6 seconds.
</script>
Upvotes: 0
Views: 95
Reputation: 3332
No point putting the background image to the index 10 of your array when it doesn't exist. Start with
document.body.style.backgroundImage = 'url(' + bgArr[9] + ')'; //any value between 0-[arraylength-1]
Upvotes: 1