javascripthtmlcssbackground-imageslideshow

Background-Image Slideshow in Js (& HTML, CSS)


I'm trying to implement a simple background image slideshow on my website but I can't find a good tutorial on the internet so I thought I'd ask here.

HTML:

<body>
   <h3>Welcome!</h1>
   <p>Lorem ipsum dolor sit amet</p>
</body>

JS:

var i = 0;
var images = [];
var slideTime = 3000; // 3 seconds

images[0] = '/img/bg1.jpg';
images[1] = '/img/bg2.jpg';
images[2] = '/img/bg3.jpg';

function changePicture() {
    document.body.style.backgroundImage = images[i];

    if (i < images.length - 1) {
        i++;
    } else {
        i = 0;
    }

    setTimeout("changePicture()", slideTime);
}

window.onload = changePicture;

CSS:

body {
    background-image: url("img/bg2.jpg");
    background-position: center;
    background-size: cover;
}

Solution

  • Background image requires URL to wrap the image file when passing an image file.

    var i = 0;
    var images = [];
    var slideTime = 3000; // 3 seconds
    
    images[0] = 'https://via.placeholder.com/150/300AAA';
    images[1] = 'https://via.placeholder.com/150/000300';
    images[2] = 'https://via.placeholder.com/150/AAA300';
    
    function changePicture() {
        document.body.style.backgroundImage = "url(" + images[i] + ")";
    
        if (i < images.length - 1) {
            i++;
        } else {
            i = 0;
        }
        setTimeout(changePicture, slideTime);
    }
    
    window.onload = changePicture;
    body {
        background-image: url("https://via.placeholder.com/150/300AAA");
        background-position: center;
        background-size: cover;
    }
    <h3>Welcome!</h3>
       <p>Lorem ipsum dolor sit amet</p>