Cycling Background Images in jQuery

Posted On: 9/19/2017 8:05:37 AM

Filed Under: Programming / Javascript

Required -
This solution will be using jQuery.  Find the CDN here: 
A crude jFiddle with the solution can be found here:

The assignment was to make a trivia game.  Easy enough, so I wanted to add some aesthetically pleasing background images that would fade and cycle into a new one, all related to the topic of trivia.  "I'll just swap out the background image I'm using and animate the opacity, right?

Well, anyone who's attempted this (for the first time) knows first-hand that the opacity property of an element affects all children.  What is the fix to this?  An independent div that we tuck back behind everything else.  

Here's what our layout will look like:

    <div class="background"></div>
    <div class="wrapper">
         <!-- rest of layout code goes here -->

Now, using CSS - we will position the background (fixed in our case) to the top-left of the screen, force its height, and set its z-index to lay behind everything.  We also need to ensure our main wrapper class lays in front of everything.  Here's our CSS:

.background {
    position: fixed;
    box-sizing: border-box;
    background: url('');  /* YOUR FIRST IMAGE HERE */
    background-attachment: cover;
    background-position: center;
    z-index: -1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

.wrapper { 
    z-index: 1;


Now, in javascript, we need to keep an array of all of our images, create a function that increments an index, makes sure it doesn't equal or exceed the length of our array, and change the background image to be that of the next item in the array, and finally, sets the interval for how many milliseconds we should fire the background change, like so (with some animation for a nice transition between images):

var backgrounds = [

var imgIdx = 0;
function swapBackgrounds() {
  if(++imgIdx >= backgrounds.length) {
  	imgIdx = 0;
  $('.background').animate({ opacity: 0}, 1000, function() {
  	$('.background').css("background-image", "url('" + backgrounds[imgIdx] + "')").animate({opacity: 1},1000);

setInterval(swapBackgrounds, 5000);

And there you have it - cycling background images!