so i have many divs with same class on the same page. i would like to add different backgrounds for each of them on my own choise(having 5-6 random backgrounds)
i found this code on the internet. but it chooses the same random color for all the divs.
<script type="text/javascript">
/***********************************************
* Random Content Colors script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
//specify list of random background colors to apply to CSS class "randomcolor"
//For each entry, you can optionally specify a text and link color via the syntax:
// "BackgroundColor:TextColor" OR "BackgroundColor:TextColor:LinkColor"
var randombgcolors=["green:white:yellow", "#DDF4FF", "#FFFF97", "#CFFF9F"]
var rbcssrule=""
var randomnum=Math.floor(Math.random()*randombgcolors.length)
if (randombgcolors[randomnum].indexOf(":")!=-1){
rbcssrule="background-color: "+randombgcolors[randomnum].split(":")[0]+";"
rbcssrule+="color: "+randombgcolors[randomnum].split(":")[1]+";"
}
else
rbcssrule="background-color: "+randombgcolors[randomnum]+";"
document.write('<style type="text/css">\n')
document.write('.randomcolor{'+rbcssrule+'}\n')
if (randombgcolors[randomnum].split(":").length==3) //if link color specified
document.write('.randomcolor a{color:'+randombgcolors[randomnum].split(":")[2]+';}\n')
document.write('<\/style>')
</script>
It looks like that code is setting its randomly chosen color to just one class: randomcolor. Assuming that all of your divs have that same class, they will all get that random color.
EDIT:
Check this JSFiddle I made, it should get you what you are looking for:
http://jsfiddle.net/VXG36/1/
HTML:
JQuery:
My understanding is that your randomnum will always be 4. When it hits your "green:white:yellow" collection it will always split into randombgcolors[randomnum].split(":")[0] which is green, and randombgcolors[randomnum].split(":")[1] which is always white. Maybe when you hit randomnum as one you need a nother randomizer to pick between 0 and 2 to get your random green:white:yellow color.