Notice: Undefined index: a777d in C:\Websites\Dduckster\index.php on line 22
Auto fading backgrounds – Dduckster

Auto fading backgrounds

Ever wanted you sites backgrounds to automatically fade between different images or textures? Well here’s a quick guide on how to do it!

You can see an example of how it looks on a live site on my Password Generator site, the background texture will change every 8 seconds.

View example

Lets get started

First off we’re going to start out with a basic website layout.
It includes a copy of jQuery (Google hosted of course), a currently empty JavaScript file, a CSS reset (in case IE wants to misbehave) and some basic centered content. All we have for a background here is a repeated tileable image and a solid colour #555 as a backup in case the images fail to load.

body{
	text-align: center;
	font-family: Arial, Helvetica, sans-serif;
	padding: 40px 0;
	background-image: url('img/BG1.png');
	background-repeat: repeat;
	background-color: #555;
}

#Container{
	margin: auto;
	width: 700px;
	background-color: #fff;
	box-shadow: 0 0 5px rgba(0,0,0,0.8);
	border-radius: 10px;
	padding: 20px 50px;
	text-align: left;
}

h1{
	text-align: center;
	margin-bottom: 40px;
}

p{
	margin-bottom: 20px;
}

Basic Layout Example

Autoload the background images

Here are the links to the 5 different backgrounds we’ll be switching between, all courtesy of Subtle Patterns.

Background 1
Background 2
Background 3
Background 4
Background 5

In our blank JavaScript file inside jQuery’s document.ready we are going to preload all the background images so there is no loading time between each background switch.

var imgArr = new Array(
	'img/bg1.png',
	'img/bg2.png',
	'img/bg3.png',
	'img/bg4.png',
	'img/bg5.png'
);

$(document).ready(function(){
	// ### Autoload BG images
	var preloadArr = new Array();
	var i;
	for (var i = 0; i < imgArr.length; i++){
		preloadArr[i] = new Image();
		preloadArr[i].src = imgArr[i];
	};
});

First we create an array of the path to each of our backgrounds. Make sure that the first one is the background you have used as the body background in the CSS.

var imgArr = new Array(
	'img/bg1.png',
	'img/bg2.png',
	'img/bg3.png',
	'img/bg4.png',
	'img/bg5.png'
);

Then we loop through each of the elements in the array and create a new image in the DOM setting the src with the value in the array. This will force the users browser to download all the images before they have been shown.

var preloadArr = new Array();
var i;
for (var i = 0; i < imgArr.length; i++){
	preloadArr[i] = new Image();
	preloadArr[i].src = imgArr[i];
};

Creating a timer

Next up we need to create a timer so that that will call a function to switch the background every 5 seconds.

We start by declaring a variable “nextBG” which will reference the next background name and another variable “BGPath” which will be set as the path to the first background in the “imgArr” array. In jQuery’s document ready we call a new function “startBGSwitch”, this will get called as soon as the browser has finished loading all it’s resources.

var imgArr = new array(...);

var nextBG = 1;
var BGPath = imgArr[0];
$(document).ready(function(){
...
	// ### Random background switcher
	startBGSwitch();
...
});

The “startBGSwitch” function simply calls setInterval which will run BGSwitch every 5000 milliseconds. setInterval is called in this function and not straight from the document ready so that we can start and stop the background switching easily.

// START BG SWITCH
function startBGSwitch(){
	setInterval(BGSwitch, 5000)
}

The first thing the called “BGSwitch” does is calculate which background to set next. We’ll be getting the background image path from the “imgArr” array using “nextBG” as an index, so we need to increment the “nextBG” value and if it’s greater than the number of backgounds we’ve got – reset it to 0.
For now we’re just going to append the value to the content of the page so we can see the counter working. You could pop up alerts instead to test but they get real annoying – fast 😀

// BG SWITCH
function BGSwitch(){
	//Increment BG
	if(nextBG >= imgArr.length - 1){
		nextBG = 0;
	} else {
		nextBG++;
	}
	//TEMP
	$('#Container').append(nextBG + '<br />');
}

So Far, So Good

I’ve knocked the timer down to 2 seconds in this example so you can see it working faster 🙂

Apply the backgrounds

Now then, to fade between images they will need to be both visible at the same time. You can’t apply two backgrounds to an element in the same place and you can’t use css3 transitions to fade between different background-image‘s. We’re going to need another element stretching across the entire screen in addition to the body.

Lets add a new div with the id BG straight after the opening body tag.

<body>
	<div class="bg"></div>
	...
</body>
#BG{
	background-image: url('img/BG1.png');
	position: absolute;
	z-index: -1;
	top: 0;
	left: 0;
	bottom: 0;
	right: 0;
}

So what’s going on here? position:absolute is pulling the div out of the document flow so that it can sit exactly where we want it. z-index: -1 is guaranteeing that the div is placed behind the page’s content and the positioning elements all set to 0 will stretch the div across the entire page. Finally, it has the same background applied as the body ready for the first switch.

Switch those backgrounds!

Time for the meat of the job. Replace your BGSwitch function from earlier with this one:

// BG SWITCH
function BGSwitch(){
	//Set the background
	$('body').css('background-image', 'url('+BGPath+')');

	//Increment BG
	if(nextBG >= imgArr.length - 1){
		nextBG = 0;
	} else {
		nextBG++;
	}

	//make bg invisible
	$('#BG').css('opacity', 0);

	//set new bg
	BGPath = imgArr[nextBG];
	$('#BG').css('background-image', 'url('+BGPath+')');

	//hardcode fix the height
	var docH = $(document).height();
	$('#BG').css('height', docH);

	//fade it back in
	$('#BG').fadeTo(3000, 1);
}

First off, before incrementing the “nextBG” value we need to set the body’s background image to the current one to get ready for the next switch.
To do this we are using the image path stored in the “imgArr” at index “nextBG”.

$('body').css('background-image', 'url('+BGPath+')');

Now we make the “BG” div transparant.

$('#BG').css('opacity', 0);

Next we update the “BGPath” with the next backgrounds path and set it to the now invisible “BG” div.

BGPath = imgArr[nextBG];
$('#BG').css('background-image', 'url('+BGPath+')');

If the pages height changes at any point say because elements have been added or removed to the page the “BG” div may no longer fit the height of the page. So we set the div’s height to the entire documents height. You could set up an event to be fired every time the documents height changes but those kind of events can be resource intensive.

var docH = $(document).height();
$('#BG').css('height', docH);

Finally, fade in the new background BG div slowly over 3 seconds.

$('#BG').fadeTo(3000, 1);

Finishing up

That’s the lot, your background should now appear to fade between different textures every 8 seconds. Click the links below to view a live example and download a zip of the examples.

VIEW LIVE DEMODOWNLOAD SOURCE

1 Comment

Leave a Reply