In my current project, I'm utilizing a library called Colorthief to extract the dominant color of an image. This extracted color is then used to dynamically set the background color of three button elements. Here's how it works:
var flag = document.getElementById("flag")
var bg_color = colorThief.getColor(flag, 5);
var tab_color = [];
for (var i=0; i < bg_color.length; i++) {
tab_color[i] = bg_color[i] - 20;
}
document.getElementById("tab-button-2").style.backgroundColor = "rgb" + "(" + tab_color + ")";
document.getElementById("tab-button-3").style.backgroundColor = "rgb" + "(" + tab_color + ")";
var selected_tab_color = [];
for (var i=0; i < bg_color.length; i++) {
selected_tab_color[i] = bg_color[i] - 35;
}
document.getElementById("tab-button-1").style.backgroundColor = "rgb" + "(" + selected_tab_color + ")";
As the project progresses, these colors are reused to update the backgroundColor of the buttons with JavaScript:
const tabs = document.querySelectorAll('[data-tab-target]');
const tabContents = document.querySelectorAll('[data-tab-content]')
tabs.forEach(tab => {
tab.addEventListener('click', () => {
const target = document.querySelector(tab.dataset.tabTarget);
tabContents.forEach(tabContent => {
tabContent.classList.remove('active');
});
target.classList.add('active');
console.log(tab.style.backgroundColor);
tab.style.backgroundColor = "rgb" + "(" + selected_tab_color + ")";
console.log(tab.style.backgroundColor);
});
});
However, this approach doesn't seem to be working as expected. Upon checking the console, it was observed that the style.backgroundColor property returns inconsistent results: firstly, an empty string despite previous assignments and secondly, the desired RGB color which doesn't reflect on the display. The inability to use predefined CSS classes for updating button colors stems from their reliance on 'tab_color' or 'selected_tab_color' variables defined earlier in the script. Can someone assist in identifying why changing style.backgroundColor isn't reflecting on the screen?
Below is the relevant HTML code snippet:
<body onload="setBgColors()">
<div id='header'>
<img src="images/ushankacat.jpg" alt="Flag" id="flag">
<h1 id="title">Fussajle</h1>
</div>
<ul class="tabs">
<li data-tab-target="#overview">
<button class="tab-button" id='tab-button-1'>
Overview
</button>
</li>
<li data-tab-target="#learn">
<button class="tab-button" id='tab-button-2'>
Learn
</button>
</li>
<li data-tab-target="#more">
<button class="tab-button" id='tab-button-3'>
More
</button>
</li>
</ul>
<div id="overview" data-tab-content class="active">
This is a test.
</div>
<div id="learn" data-tab-content>
Learn blah blah blah
</div>
<div id="more" data-tab-content>
Something something something.
</div>
</body>
Your guidance would be highly appreciated.