How to Make the Background Image Change Randomly

If you have a webpage with a tiled background image, you can make the background alternate randomly among a set of images. For example, this webpage has a randomized background image; if you refresh it several times, you will see different patterns on the page margins. All you need to do is create the image files and add a simple JavaScript code in the header of your webpage.

First, assemble the background image files in the same directory and rename them so that they all have the same name except with different numbers appended to the end of the name. It is better if the images all have the same file extension as well (.png, .jpg, .gif).

For instance, if you want to rotate randomly among five different background motifs, name them

mybg1.png
mybg2.png
mybg3.png
mybg4.png
mybg5.png

Next, locate the following line of code somewhere between the <head> and </head> tags in the header of your page:



You must place the JavaScript code somewhere after this line and before the </head> tag. This ensures that the code will override any background styles set in the external CSS file.

Now just copy and paste the following code:



The "background-attachment:fixed" command prevents the tiled image from moving when you scroll down the page. If you want the image to move when you scroll, you can erase that part.



© Had2Know 2010