0

What would be the best way to have an array of background images and loop through them using js/jquery in an infinite loop?

this is what I have so far:

//ANIMATE JUMBOTRON BACKGROUND IMAGE
$(document).ready(function() {
    var backgroundImage = [
        'url(/static/images/slideshow/slide0.jpg)',
        'url(/static/images/slideshow/slide1.jpg)',
        'url(/static/images/slideshow/slide2.jpg)',
        'url(/static/images/slideshow/slide3.jpg)',
        'url(/static/images/slideshow/slide4.jpg)'
    ];
    $('.jumbotron').css('background-image', backgroundImage[0]);
})

this is obviously just the array and simple css, but I am a bit lost on how to loop through the array?

Sandra Willford
  • 3,459
  • 11
  • 49
  • 96
  • [setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) –  Sep 18 '17 at 16:16
  • See [Trying to make multiple background images cycle through a slideshow with CSS and JQUERY](https://stackoverflow.com/questions/30388118/trying-to-make-multiple-background-images-cycle-through-a-slideshow-with-css-and/) – guest271314 Sep 18 '17 at 16:22

2 Answers2

2

A counter variable and a window.setInterval should do you. Increment the counter every time the interval'd function runs - once you hit the length of the background image array reset it back down to 0.

var backgroundImages = [
    'url(/static/images/slideshow/slide0.jpg)',
    'url(/static/images/slideshow/slide1.jpg)',
    'url(/static/images/slideshow/slide2.jpg)',
    'url(/static/images/slideshow/slide3.jpg)',
    'url(/static/images/slideshow/slide4.jpg)'
],
backgroundImageCounter = 0,
jumbotron = $('.jumbotron');

window.setInterval(function() {
    jumbotron.css('background-image', backgroundImages[backgroundImageCounter]);

    backgroundImageCounter++;
    if(backgroundImageCounter >= backgroundImages.length) {
        backgroundImageCounter = 0;
    }
}, 5000);
Scoots
  • 3,048
  • 2
  • 21
  • 33
0

There is this thing called setInterval.

var count = 0;
var div = document.getElementById('a');
var btn = document.getElementById('b');

var interval = setInterval(function(){
        div.innerText = count;
        count++;
    }, 1000);
    
btn.addEventListener('click', function(){
    clearInterval(interval);
});
<div id="a">0</div>

<button id="b">Stop</button>
yqlim
  • 6,898
  • 3
  • 19
  • 43