How to Set Random Website Background Colors With JavaScript

Here’s an example JavaScript code snippet to set random website background colors. In this case, we will choose a random string (color) from an array and set it as the background color of the <body> tag.

<script>

    var bgcolor = function(param) {
        var names = ['f5deb3','fab1a0','BDC581','9AECDB','CAD3C8', 'ffcccc'];
        var random=  Math.floor((Math.random() * names.length));
        var randomColor = names[random];

        const addCSS = css => document.head.appendChild(document.createElement("style")).innerHTML=css;
        addCSS("body  { background:#" + randomColor + "!important; }")       

    };

    bgcolor({
    });

</script>

Cover Photo by Joan Gamell on Unsplash

Written by MighilMighil is an indie musician and tinkerer with diverse work experience in technology and writing. He has had the privilege of serving in various capacities, encompassing generalist and specialist roles. He is currently based in Chengdu.

Newsletter

Opt-in to receive long-form essays in your inbox. Unsubscribe anytime. Follow me on 𝕏 if you like.

Powered by DigitalOcean, BunnyCDN, WordPress.