How to get random background (in JavaScript)? That's what I do here!


In order to be more efficient I choose to write some Functions.


We need a function which return a list of link (or filename) to use as background.

 * Return a list of URL
function backgrounds() {
    // We create a variable
    var imageURLs = [
        // We assign in an array the list of URL/filename we want as background

    // We return the created variable
    return imageURLs;


We need a function that return a random in range [0-x] where x is the length of backgrounds().

 * Return a random number in range [0-x] where x is the length of backgrounds
 * @param {int} max
 * @returns {int}
function randomNumber(max) {
    return Math.floor((Math.random() * max));


We need a function that return a background from backgrounds() with randomNumber() as index.

 * Get a random url from backgrounds
 * @returns {str}
function getBackground() {
    var numberOfImages = backgrounds().length,
        uniqueNumber = randomNumber(numberOfImages);
    return backgrounds()[uniqueNumber];


we need a function that return a well formatted css for the background.

 * show background on screen
 * @returns {DOM}
function showBackground() { = "url('" + getBackground() + "')"; = "center center"; = "no-repeat"; = "fixed";

Load all on page loading

// On load, we show the background on screen
window.onload = showBackground();

Final script

Known issue

This script doesn't work on safari.