EDIT: I KIND OF FIGURED IT OUT CODE HERE STILL SOME ISSUES (has to be 255 objects right now):
for (let i = 1; i <= 255; i++) {
let arg = document.createElement("div");
let red = 0;
let green = 0;
let blue = 0;
if (color == 0) {
red = 255;
green = num * 3;
} else if (color == 1) {
red = 255 - num*3;
green = 255;
blue = num * 3;
} else if (color == 2) {
red = num * 3;
green = 255-num*3;
blue = 255;
}
arg.style.backgroundColor = "#" + htd(red) + htd(green) + htd(blue);
document.querySelector("body").appendChild(arg);
if (num == 85) {
num = 1;
color++;
} else {
num++;
}
}
OLD QUESTION
I am generating a number of HTML objects in JS using a for loop. I want these objects to progressively be colored from red to purple (rainbow order). How would I go about going from #FF0000
to #008080
and back again to #FF0000
.
Here is my code so far (DOESN'T WORK WELL):
for (let i = 1; i < 255; i++) {
let arg = document.createElement("div");
let num = i;
if (num > 255) {
num = 255;
}
let red = 255;
let blue = 0;
if (num < 128) {
let green = 0;
arg.style.backgroundColor = "#" + htd(red - i) + htd(green + i * 2) + htd(blue + i);
} else {
let green = 256;
arg.style.backgroundColor = "#" + htd(red - i * 2) + htd(green - i * 2) + htd(blue + i);
}
document.querySelector("body").appendChild(arg);
}
function htd(num) {
let hexString = num.toString(16);
if (hexString.length % 2) {
hexString = '0' + hexString;
}
return hexString;
}
If you want to see why I need this go to https://codepen.io/navinate/pen/dwExxm
Thank You!