jQuery – Random Background Color with Opacity on each Div

If you have a grid of boxes on a page, for example, and you want every box to have a randomly assigned / different background color, here is the script. Change out MYDIV for whatever your div is called.

The example below with give you transparency on the background color using RGBA, and a value of 80% opacity (value= .8).

If you want solid color with no transparency, change .8 to 1 for 100% opacity, or change rgba -> rgb and ‘,.8)’-> ‘)’

$(document).ready(function() {
    $('.MYDIV').each(function () {
        var hue = 'rgba(' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',' + (Math.floor((256-199)*Math.random()) + 200) + ',.8)';
        $(this).css("background-color", hue);
    });
});

2 thoughts on “jQuery – Random Background Color with Opacity on each Div”

Leave a Reply