Javascript to change background onload randomly

You can change the background image of a web page automatically each time the page is loaded or reloaded.

Using javascript you can do it independently of server configurations, even locally, on web pages you have on your PC.

A nice feature of this script is that you don’t need to have specific names in your images, such as a series of numbers (1.jpg, 2.jpg, 3.jpg, etc.), and you don’t need to put each image in a numbered array, even keeping its name (such as image1=”/some-address/some-name.jpg”, image2=”……”, etc.).

All you have to do is copy the full address of your images, have each address inside quotes, and separate each quote by a comma.

Even if you are going to use hundreds of images in this random automatic change of background, you can configure the script in less than 5 minutes!

Just don’t forget that on-line images should have an address like https://etc., while images on your disk, in case that you build a local web page, should have an address like “file:///X:/somefolder/etc.”

To use the script, copy and paste it before the closing tag in your web page. Then in the body tag define the onload event as explained below.

[sociallocker message=”Share, and Get the Script”]
In the head of the web page:
<script type=”text/javascript”>
function backgrounds() {
var imageURLs = [
“file:///X:/somefolder/somename.jpg”, “”
return imageURLs;
function randomNumber(max) {
return Math.floor((Math.random() * max));
function getBackground() {
var numberOfImages = backgrounds().length,
uniqueNumber = randomNumber(numberOfImages);
return backgrounds()[uniqueNumber];
function showBackground() { = “url(‘” + getBackground() + “‘)”; = “center center”; = “no-repeat”; = “fixed”;
In the body tag define the onload event as: onload = “showBackground();”