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); }); });
hey there, How can i make it possible to run the code where in the page are divs with same class generated from the code, how can i add a foreach ?
Here in the code, change .MYDIV to the name of the class you want to target:
$('.MYDIV').each