springmile’s blog

Posted
21 June 2008 @ 7pm

Tagged
JavaScript

Random background images

With the release of Firefox 3 Mozilla Europe introduced a new design. Very much my test fr this type of product.

One of the thing I like is the random background image on the home page. As I’ve been doing something similar recently for my portfolio site I was curious how the guys at Mozilla approached this.

The solution is basic but elegant and thought to share it here. “variation1″, “variation2″, “variation3″ are CSS classes with different background images.

<script type="text/javascript">
// <![CDATA[
// Add a class to the body tag to alternate background features
var class_options = new Array( "variation1", "variation2", "variation3" );
 
if (Math.random) {
  var choice = Math.floor(Math.random() * (class_options.length));
 
  // Just in case javascript gets carried away...
  choice = ( (choice < class_options.length)  && choice >= 0) ? choice : 0;
 
  if (document.body.className == '') {
    document.body.className = class_options[choice];
  } else {
    document.body.className += ' '+class_options[choice];
  }
}
// ]]>
</script>

No Comments Yet


There are no comments yet. You could be the first!

Leave a Comment

The dead of the contact form Web 2.0 … The Machine is Us/ing Us