Created
December 14, 2012 21:40
-
-
Save rs77/4288884 to your computer and use it in GitHub Desktop.
A simple background-image slider made with jQuery and Underscore in WordPress (inserted before the closing `</body>` tag). More details here: http://www.webbyworks.com.au/41/a-simple-jquery-background-image-slider
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment