How To Create A Simple jQuery Background Image Slider

In one recent project I had to incorporate a traditional slider on the front page of a WordPress installation to showcase the range of products this site was selling. I was a little lazy and bought a popular package to accommodate the needs of my clients’ request.

Unfortunately though, after tinkering around with it, I found it more of a nuisance than a help. Even after setting the package to use no styling it was still difficult to manipulate the object’s css properties to do what I wanted.

In the end I thought to myself, Why don’t I just roll my own?

My requirements weren’t that complicated.

All I needed was something that could do the following:

  • Randomly loop through a set of images (and then keep that rotation)
  • FadeIn and FadeOut of the images (the client didn’t need anything fancy)
  • Images that are confined to the width and height of the div element (if the image is too small, stretch it, if it’s too big shrink it)

I found by using the background CSS properties on a div element perfect for my needs. Here’s the resulting output:

The only HTML needed:

<div class="my-bg-slider"></div>

The CSS on this object needed:

.my-bg-slider { 
    background: url("/wp-content/uploads/2012/10/DSC_011.png") no-repeat; 
    width: 960px; 
    height: 640px; 
    background-position: top left; 
    background-size: 100%; 
}

Obviously the URL of the image, the width and height properties can all be changed to suit your needs.

The JavaScript

Placed above the </body> tag:

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore-min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
// check to see if the page contains this element
if ( $('.my-bg-slider').length > 0 ) {
// insert the URIs of all the images you wish to include in the slider here:
var backgroundImages = [ 'http://www.example.com.au/wp-content/uploads/2012/12/DSC_02461.jpg',
'http://www.example.com.au/wp-content/uploads/2012/11/DSC_0161_1.jpg',
'http://www.example.com.au/wp-content/uploads/2012/12/DSC_0587.jpg',
'http://www.example.com.au/wp-content/uploads/2012/12/DSC_0293.jpg' ];
// get the existing backgroundImage of the div element
var existingImage = $('.my-bg-slider').css('background-image');
existingImage = existingImage.replace('url(','').replace(')','');
// remove the existing image from the backroundImages list (if it's there)
var tempArr = _.without(backgroundImages, existingImage);
// randomly shuffle the remaining images
var randomImages = _.shuffle(tempArr);
// load the new images in the background to speed up transfer
for ( var a = 0; a < randomImages.length; a++ ) {
$('<div class="temp-imgs">').appendTo('div.my-bg-slider').html('<img src="' + randomImages[a] + '" />').css("display", "none");
}
// insert existingImage to the front of the shuffled list
randomImages.unshift(existingImage);
var i = 0; // needs to start at the next list item (not 0)
setInterval(function() {
i++;
// check to see if we're now at the end of our slider image array
// if so, start back at the start again
if ( i === randomImages.length ) { i = 0; }
var img = "url(" + randomImages[i] + ")";
// fadeOut the current image then replace the backgroundImage then fadeIn
$('.my-bg-slider').fadeOut(1000, function() {
$('.my-bg-slider').css('background-image', img);
});
$('.my-bg-slider').fadeIn(1000);
}, 3500);
}
});
</script>
view raw simple-bg-slider.js hosted with ❤ by GitHub

Conclusion

As you can see it’s a relatively simple jQuery slider that uses Underscore.js to help with the array utilities.

Have a play around with it and let me know how you go. Of course, there are several ways to extend this by having an array of objects instead of an array of strings and then using the settings of the object to change the type of effect, adding content on the slide (etc).

You never know maybe the client will want extended functionality on the home page slider! At the moment, it meets the intended purpose.