JavaScript CSS Random Background Image

I have created this little JavaScript function that takes a div (or whatever) and randomly changes the background image after a specified time. It's fully unobtrusive & degradable, but you must set a background image in your CSS file for the element you are going to do this on (Which you should have done anyway, hence why you're trying to change it!); so if the users do not have JavaScript enabled they will just see the original background image.

You can download the code here, and simply include it in your HTML page and voila - Below we'll walk through what needs to be changed

Firstly the variables:

var MyElement = "Put the ID of the element you want to change here"
var ImgPath = "The image path to your file.. ie. /img/"

The array: holds all of your images you want to use, everytime you add a new image don't forget to update the array number i.e..

random_images[0] = "header.jpg";
random_images[1] = "header2.jpg";
random_images[2] = "header3.jpg";

The timer:

movement = setTimeout("ChangeCSSBgImg()",14000);

The time is in milliseconds, so 14000 is 14 seconds and 5000 would be 5 seconds and so one.
Right here's the full code... Either download it here or copy and paste the below

 

/* Script taken from leemessenger.co.uk - Please do not remove this line */

function ChangeCSSBgImg() {
if (!document.getElementById) return false;

var MyElement = "YOUR ID HERE" //The ID of the element you want to change
var ImgPath = "YOUR FILE PATH" //The file path to your images

if (!document.getElementById(MyElement)) return false;

var random_images = new Array ();
random_images[0] = "YOUR IMAGE.JPG";

var $header = document.getElementById(MyElement);
var $backgroundurl = $header.style.backgroundImage;
var ImgURL = "url(" + ImgPath + random_images[rand(random_images.length)] + ")";

if ($backgroundurl != ImgURL) {
$header.style.backgroundImage = ImgURL;
}

movement = setTimeout("ChangeCSSBgImg()",14000);
}

/* random number generator */
function rand(n) {
    return ( Math.floor ( Math.random ( ) * n ) );
}

/* Custom onload function */

function addLoadEvent(func) {
    var oldonload = window.onload;
        if (typeof window.onload != 'function') {
        window.onload = func;
        } else {
        window.onload = function() {
    oldonload();
func();
}
}
}

/* trigger onload */

addLoadEvent(ChangeCSSBgImg);

Don't get me wrong, this is still not an ideal solution but I'll be updating it when I get a chance.

Hope someone is able to use it

Comments

June 12. 2008 19:43

This is great! Please work on it so good, because I've begin testing it on a e-commerce site as well! Go for it!

Felu

August 11. 2008 19:48

Do you by chance have an online example of this at work?

Nielle McCammon

Add comment


 

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]