Wow old school all round.
Don't use document.write
. Its designed to create the markup on the fly and is very inefficient.
You can create a table using table = document.createElement("table")
and add rows with row = table.insertRow()
and add cells to rows with cell = row.insertCell()
. When the table is complete add it to the document with document.body.appendChild(table)
or to a containing element tableContainer.appendChild(table)
To create an arrays, use array literals. Eg hex = ["00", "33", "66", "99", "Cc", "Ff"]
To add the color as text in the table cells you just set the cells textContent
property. However as you have a large range of colors you will need to ensure that the color of the text does not match the color of the background.
You can do this by adding the red green and blue values. If they add to under a threshold set the text color to white, else to black. Best to use a bold font. eg "arial black"
The example bumps the rgb values for the text color test to account for human perceptual color sensitivity (its a rough estimate)
function webSaveColorTable() {
const table = document.createElement("table");
const hex = [0, 0x33, 0x66, 0x99, 0xCC, 0xFF];
const toHex = val => val.toString(16).toUpperCase().padStart(2,"0");
const width = 100, height = 55;
for (const red of hex) {
for (const green of hex) {
const row = table.insertRow();
for (const blue of hex) {
const colBg = "#" + toHex(red) + toHex(green) + toHex(blue);
const c = Object.assign(row.insertCell(), {textContent: colBg, width, height});
Object.assign(c.style, {
backgroundColor: colBg,
color: red * 0.2 + green * 0.7 + blue * 0.1 > 128 ? "#000" : "#fff"
});
}
}
}
document.body.appendChild(table);
}
webSaveColorTable();
body {
font-family: arial black;
}
td {
text-align: center;
}