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

About Steven Chu


Hi, I'm Steven! I'm an entrepreneur, photographer and art director in New York. Follow this blog for self expression, fun, and most importantly: looking comfortable, at ease, and amazing in your photos no matter who takes them! I dedicate this to my amazing friends who have let me inadvertently turn all of our hangouts and travel photos into a never ending photoshoot of fun. The proof is in the pudding-- our photos rock. My other projects: I'm the founder of InstaTechie.com, a face-to-face tech concierge service for NYC. Book a techie to walk you through something you want to learn! My work focuses on socially engaged art projects which use technology to create access to resources for communities. Visit Steven Chu Studio (stevenchustudio.com) for branding & design work or Steven Chu (stevenchu.com) for photography projects.

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

Leave a Reply