I am attempting to create a subheader with varying colors, similar to the one found on the Ask Different page. However, instead of manually assigning colors, I am looking to have it randomly select a color from a Javascript array.
I have already outlined the hexadecimal colors I wish to utilize, but I am encountering difficulty with displaying it correctly (or at all) on the HTML page. Could someone provide guidance on how to resolve this issue? If jQuery can achieve this, that would be acceptable as well.
My current progress:
Javascript:
var colors = ['#3399FF', '#44A1FF', '#55AAFF', '#65B2FF', '#76BBFF', '#87C3FF', '#98CCFF', '#A9D4FF', '#BADDFF', '#CAE5FF', '#DBEEFF', '#ECF6FF'];
onload = changeColor();
function changeColor() {
subheader.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
}
HTML:
<div class="header"></div>
<div class="subheader" id="sub1"></div>
<div class="subheader" id="sub2"></div>
<div class="subheader" id="sub3"></div>
<!-- Repeats till id="sub20" -->
CSS:
.header {
width:100%;
height:10%;
position:absolute;
background-color:#3399FF;
left:0;
top:0;
}
.subheader {
height:2%;
width:5%;
top:10%;
position:absolute;
}
#sub1 {left:0;}
#sub2 {left:5%;}
#sub3 {left:10%;}
/* Repeats till #sub20 */
If there is a way to streamline my extensive HTML and CSS code, possibly using something like :nth-child()
, please advise on that as well. Thank you, any assistance is welcomed.