Background Image Daily Rotation
A HunBug Document
Last Updated: 01 Apr 2008
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 consists of just the one line. It sets the background image style property of the element passed to it.
node.style.backgroundImage = "url(\""+images[Math.floor(new Date().getTime()/86400000)%images.length]+"\")";
<h1>Daily Background Image</h1>
var imgArray = new Array();
imgArray = "images/strech.jpg";
imgArray = "images/pat.jpg";
imgArray = "images/rusty.jpg";
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
The example over sets the background image of the document body, however any element that can have the style property set can be used.
If a random image is required the function can be changed to select from Math.random rather than the date.
StyleThere 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.