Randomize background of a webpage

Suppose that you have a landing page (or just a cool background) and you have some many versions of it, and all so beautiful, that you can’t decide which one to show. Some kind of weird solution is to show them all in a random manner.

If you wish to achieve something similar to this then all you need is a really short piece of HTML, JavaScript and CSS. All can be put to a single file.

Since I like a clean and easy solution, this one use pure-JavaScript. No jQuery stuff etc. included.

HTML

Get as simple HTML file as it can be:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Niner Games</title>
</head>
<body id="body">

</body>
</html>

CSS

Add some simple styling inside <head>, below <title>:

<style>
    body { 
       width: 100%; 
       height: 100%; 
       background: url('chromatic.jpg') no-repeat fixed center center / cover;
    }
</style>

JS

Now add some magic / JavaScript below closing </body> tag:

<script>
    /**
     * Randomize background.
     * 
     * https://onezeronull.com/2022/02/08/randomize-background-of-a-webpage/
     */
    function l() {
        var
            f = ['chromatic.jpg', 'galaxy.jpg', 'lights.jpg', 'paint.jpg', 'sky.jpg'],
            r = Math.floor(Math.random() * f.length),
            s = "background: url('" + f[r] + "') no-repeat fixed center center / cover";
        
        document.getElementById("body").setAttribute('style', s);
    }

    window.onload = l;
    window.onresize = l;
</script>

The whole code

The entire file could look like that:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Niner Games</title>
    
<style>
    body { 
       width: 100%; 
       height: 100%; 
       background: url('chromatic.jpg') no-repeat fixed center center / cover;
    }
</style>
</head>
<body id="body">

</body>
<script>
    
    /**
     * Randomize background.
     * 
     * https://onezeronull.com/2022/02/08/randomize-background-of-a-webpage/
     */
    function l() {
        var
            f = ['chromatic.jpg', 'galaxy.jpg', 'lights.jpg', 'paint.jpg', 'sky.jpg', 'snow.jpg', 'sunset.jpg'],
            r = Math.floor(Math.random() * f.length),
            s = "background: url('" + f[r] + "') no-repeat fixed center center / cover";
        
        document.getElementById("body").setAttribute('style', s);
    }

    window.onload = l;
    window.onresize = l;
</script>
</html>

All that you have to do is to place corresponding files in the same folder as your .html file.

Leave a Reply