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 Mighil — Mighil is a Rolling Stone-featured 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 and working on AI and tech projects.

Newsletter

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

Powered by DigitalOcean, BunnyCDN, WordPress.