Oz Cohen Oz Cohen - 6 months ago 10
HTML Question

cant add more images to the script

how can i had mor images?

<script>
var rotate = false;

function setbackground() {
newImage = rotate ? 'url(mimages/wallpaper2.jpg)' : 'url(mimages/shutterstock_105126044-795x380.jpg)';
rotate = !rotate;
document.getElementById('change').style.backgroundImage = newImage;
}

setInterval(setbackground, 4000);
</script>


i tried add the same way with :
did not worked

Answer

There are a few ways you could go about this. I'd recommend storing the url's of the images in an array, and incrementing a counter on each subsequent call of setBackground().

var images = [
    "url('mimages/wallpaper2.jpg')",
    "url('wallpaper2.jpg')",
    "url('wallpaper3.jpg')"
];

var imageIndex = 0;
function setbackground() {
             newImage = images[imageIndex];
             document.getElementById('change').style.backgroundImage = newImage;
             if (imageIndex != images.length){
                 imageIndex++;
             }
             else{
                 // If we've reached the end of the array, reset the index
                 imageIndex = 0;
             }
             document.getElementById('change').style.backgroundImage = newImage;
}

setInterval(setbackground, 4000);

When you want to add more images, simply add a new entry in the array.