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.


    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; }")       




Cover Photo by Joan Gamell on Unsplash

Email [email protected] or wechat: mighil to work together. I can help you with content, product ops, scripting, strategy, and technology.

Random: something I've read, browsed, or watched.

*Previously Powered by DigitalOcean, GeneratePress, and BunnyCDN.