Clever Background Changes

On our new site, we cycle through a handful of different background images. At first, we were just randomizing, but with any randomness, you get the potential of it not seeming random: seeing the same image more than once, or not seeing one very frequently. (see Radiolab’s Stochasticity episode for a great, semi-related discussion)

Anyway, I had the clever idea to use a bit of Javascript to make it go through in a specific order instead. This lets people see all the images before they see duplicates, and also lets us ensure they see the best ones first.

Brandon coded it up nicely in jQuery:

var backgrounds = [
  "/assets/background1.jpg",
  "/assets/background2.jpg",
  "/assets/background3.jpg",
  "/assets/background4.jpg"
];

var index = +$.cookie('bg');
if(index >= backgrounds.length) { index = 0; }  
$('img.background').attr('src', backgrounds[index]);
$.cookie('bg', index + 1);

We simply set a cookie with the index of the current background you’re viewing. Then on each page load, move on to the next one.

Some people might scoff at using a cookie for a simple index, but we think its worth it.

Have a more clever idea? Let us know!

Photo of Daniel Morrison

Daniel founded Collective Idea in 2005 to put a name to his growing and already full-time freelance work. He works hard writing code, teaching, and mentoring.

Comments

Add a Comment

Hmm...that didn't work.

Something went wrong while adding your comment. If you don't mind, please try submitting it again.

Comment Added!

Your comment has been added to this post. Please refresh this page to view it.

Optional. If added, we will display a link to the website in your comment.
Optional. Never shared or displayed in your comment.
  1. June 12, 2010 at 1:18 AM

    Instead of the cookie you could use the new HTML5 Storage.
    I think this will have the extra advantage of not adding a cookie to the http request.

  2. June 12, 2010 at 8:35 AM

    Hansv: Ooh, good idea!  I’ll definitely try that out, and I can fall back to a cookie for older browsers.