Background Image Daily Rotation

A HunBug Document
Document No.: 11500
Last Updated: 01 Apr 2008
Author: HunBug

This function allows you to change background images on a daily basis. The same image will be selected for a day, then a different image the next day, until the cycle begins again.

The Function

The function consists of just the one line. It sets the background image style property of the element passed to it.

<html>

  <head>

    <script>

      function dailyBackground(node,images)
      {
        node.style.backgroundImage = "url(\""+images[Math.floor(new Date().getTime()/86400000)%images.length]+"\")";
      }

    </script>

  </head>
 
  <body>
 
    <h1>Daily Background Image</h1>
   
    <script>
   
      var imgArray = new Array();
      imgArray[0] = "images/strech.jpg";
      imgArray[1] = "images/pat.jpg";
      imgArray[2] = "images/rusty.jpg";

      dailyBackground(document.body,imgArray);
     
    </script>
 
  </body>
 
</html>
 

The image paths need to be entered into an array, imgArray, this is then used by the function to select the background image. You can add as many images as you wish, just increment the number in the square brackets. 

The dailyBackground function accepts two parameters:

  • node: This is the element to apply the backgroundImage to. In this example the document body is  used.
  • images: This is a reference to the array which contains the images

Variations

The example over sets the background image of the document body, however any element that can have the style property set can be used.

dailyBackground(document.getElementById('myDiv'),imgArray);

If a random image is required the function can be changed to select from Math.random rather than the date.

node.style.backgroundImage = "url(\""+images[Math.floor(Math.random()*images.length)]+"\")";

Style

There are several style sheet properties to control the appearence of the background image:
  • background-attachment: scroll , fixed, inherit
    • This defines whether the background should scroll with the element or be fixed if the element scrolls.
  • background-image: <url>, none, inherit
    • The is used by the function to set the background image.
  • background-position: [ <percentage>, <length>, left, center, right ], [ <percentage>, <length>, top, center, bottom ]
    • This property takes two parameters to position the initial image. Tiled image positions will be calculated from this image if repeating has been set.
  • background-repeat: repeat, repeat-x, repeat-y, no-repeat, inherit
    • This defines the tiling pattern for the image.

Further Reading

Seasonal Background: A variation on this function, that changes the background image dependant on the season.
Fade Slideshow: More image controls, this time displaying an array of images as a slide show.

HunBug Store








Comments are all individually read, none are automatically posted to the site.