Simple jQuery image / banner randomizer script

It’s quite a common thing for people to use some kind of script to randomize a banner. In fact when I first started doing that I was using Flash ActionScript to do my work for me? What the hell, ‘WHY’ you ask?!? I was heavily into Flash and AS2 at the time…

Anyway, I used to use conventional JavaScript. Here is a script that I put together probably about 4+ years ago;

function image() { }; image = new image(); number = 0; 
// imageArray - keep adding items here... 
image[number++] = "I"
image[number++] = "I"
image[number++] = "I" 

// This does all the maths - the genius part
increment = Math.floor(Math.random() * number); 
document.write(image[increment]);

Clearly, this is very crude, no externalization of CSS all inline, the images not controlled centrally via an array, need I go on? No.

Then jQuery pop’s it super intelligent nose onto the scene. So I wrote (eventually – I was from the if it is not broke don’t fix it era you know 😉 ) the function in that.

// Your images are in the array 
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];

You use the array either in this way (read the comments);

// You can either set your image as back of the HTML element background style attribute 
$('#site-banner').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'});

Or like this;

// Or insert the image instead 
$('').appendTo('#site-banner');

There are some assumptions made in the code;

  • The name of your HTML element has an ID of ‘site-banner’
  • The path of your images folder is ‘images/’

Now that I accomplished that great and wonderfully simple feat I declare this job done, now we can all go out to play.

1 Comment

  1. Rachida says:

    The paragon of understanding these issues is right here!

Leave a Reply

Your email address will not be published. Required fields are marked *