Impossibly simple image randomizer with jQuery
Reading time: About 1 minute
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.
1 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.
1 $('#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.
1 $('<img src="images/' + images[Math.floor(Math.random() * images.length)] + '">').appendTo('#ad');
12 comments skip to comment form
Jim Gaudet said— 10 hours later
Bruno Correia said— 12 hours later
Design Informer said— 14 hours later
Brian J King said— 22 hours later
Brian Cray said— 22 hours later
Brian Cray said— 1 day later
Design Informer said— 2 days later
Erik Ford said— 2 days later
Design Informer said— 2 days later
Jim Gaudet said— 1 week later
Steve said— 2 weeks later
Webdesign Rosenheim said— 1 month later
Respond to this post—