Dylan Dylan - 5 months ago 20
CSS Question

Rotate background-image url every 10 seconds

I've seen a lot of similar questions but couldn't find a resolution. I have a bootstrap jumbotron and a set of 3 images to cycle through it every 10 seconds. The problem is that the first url doesn't show until the first 10 seconds has passed. After the array finishes the images play correctly, it's only on first load that the image is blank. I've tried setting the background-image via CSS and JQuery, but still encountered issues with skipping when loading the first image.

The Code



var jumbotronBG = ['/image1.jpg', '/image2.jpg', '/image3.jpg'];
var changeImage = $(".jumbotron");
var i = 0;

setInterval(function() {
changeImage.css({'background-image': 'url(' + jumbotronBG[i] + ")"});
i = i + 1;
if (i == jumbotronBG.length) {
i = 0;
}
}, 10000);

<div class="jumbotron">


</div>





Just need to find a way to cycle all 3 images with the fist being image1.jpg when the page loads.

Answer

I don't see anything wrong except for not calling the background-image change on load? Changed JavaScript code to fix this:

var jumbotronBG = ['https://placehold.it/100x100', 'https://placehold.it/200x200', 'https://placehold.it/300x300'];
var changeImage = $(".jumbotron");
var i = 0;

function cycleImage() {
  changeImage.css({
    'background-image': 'url(' + jumbotronBG[i] + ")"
  });
  i = i + 1;
  if (i == jumbotronBG.length) {
    i = 0;
  }
}

setInterval(cycleImage, 1000);
cycleImage();

This JSFiddle works as you intended right?

Comments