Written by Brian Cray on December 28th, 2009
A common design pattern—if you want to call it that—is to display a random header image or advertisment on each new pageview. I'm always looking for ways to simplify code [see 1, 2, 3], and naturally, I tried to do it here.
Today's impossibly simple code turns the task of image randomization into a 1-line jQuery code snippet. Awesome.
1. Start with an array of images
Change the image filenames in the array to the actual filenames. Don't include the directory—filenames only.
var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];
2a. Set a random header background with jQuery and CSS background-image
The following code assumes your header has an ID of #header and your images directory is just "/images". Change them if necessary.
$('#header').css({'background-image': 'url(images/' + images[Math.floor(Math.random() * images.length)] + ')'});
2b. Insert a random advertisement with jQuery and DOM injection
The following code assumes your ad container has an ID of #ad and your images directory is just "/images". Change them if necessary.
$('<img src="images/' + images[Math.floor(Math.random() * images.length)] + '">').appendTo('#ad');