Note on title: I really did not know how to perfectly name this question. If someone can suggest a more appropriate title, please do.
I have a table where headers must be colored based on the first 7 characters of their name.
First 7 characters are yyyy.mm. For example 2017.10.
Here is my need:
- I want every occurrence of same 7 chars to be the same color (cell's background color). In other words, if cell's first 7 chars are 2017.10 - they all should be the same color. If it is 2017.09, they all should be the same color BUT different from 2017.10 or any other date.
I am trying to do it but having really hard time finishing it. I feel like I am close...
JS:
function setHeaderColor() {
const mainTable = document.getElementById('main-table');
const headerRow = document.querySelectorAll('#main-table tr:first-child th');
const test = []; // Holds first 7 chars and background color of each column header
const colors = [
'#FF6633', '#FFB399', '#FF33FF', '#FFFF99', '#00B3E6',
'#E6B333', '#3366E6', '#999966', '#99FF99', '#B34D4D',
'#80B300', '#809900', '#E6B3B3', '#6680B3', '#66991A',
'#FF99E6', '#CCFF1A', '#FF1A66', '#E6331A', '#33FFCC',
'#66994D', '#B366CC', '#4D8000', '#B33300', '#CC80CC',
'#66664D', '#991AFF', '#E666FF', '#4DB3FF', '#1AB399',
'#E666B3', '#33991A', '#CC9999', '#B3B31A', '#00E680',
'#4D8066', '#809980', '#E6FF80', '#1AFF33', '#999933',
'#FF3380', '#CCCC00', '#66E64D', '#4D80CC', '#9900B3',
'#E64D66', '#4DB380', '#FF4D4D', '#99E6E6', '#6666FF'
];
headerRow[1].style.backgroundColor = colors[1];
// Extract first 7 characters from column header name
for (let i = 0; i < headerRow.length; i++) {
test.push({
version: headerRow[i].innerHTML.substring(0, 7),
color: headerRow[i].style.backgroundColor || null
});
}
for (let i = 1; i < test.length; i++) {
if (test[i].version === test[i - 1].version) {
test[i].color = test[i - 1].color
} else {
test[i].color = colors[Math.floor(Math.random() * colors.length)];
}
}
for (let i = 0; i < headerRow.length; i++) {
headerRow[i].style.backgroundColor = test[i].color;
}
}
document.addEventListener('DOMContentLoaded', setHeaderColor);
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<table class="w3-table-all" id="main-table">
<tr>
<th class="w3-center"> Name</th>
<th class="w3-center">2017.10-T-2018_08_30 ms_201709.</th>
<th class="w3-center">2017.09-T-2018_08_30 ms_201709.</th>
<th class="w3-center">2017.10-T-2018_08_30 ms_201709</th>
<th class="w3-center">2017.09-T-2018_08_30 ms_201709</th>
<th class="w3-center">2017.08-T-2018_08_30 ms_201709</th>
</tr>
</table>
As you can see, every time colors are different. What I am doing now is comparing cell to the previous cell ([i - 1]
). I know I should be checking whether this value exists in an array test
and then getting its associated color, but I cannot come up with a way to do that. I tried indexOf
, includes
and no success...