The background color property returns as blank, failing to update on the screen despite my attempt to assign a new value

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.

Answer №1

My assumption is that the issue may lie with the variable selected_tab_color, which was initially declared as an array and had values added to it. However, it seems that later in the code, you are trying to access it as a number.

Furthermore, it appears that earlier on, you configured background colors for button elements, but within the forEach loop, you are setting them for li elements instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using incompatible style attributes with React-Awesome-Slider in Gatsby

I recently incorporated React Awesomeslider into my project, which is developed using Gatsby.js and Next.js, with Sanity.io as the CMS. The css styling is currently set up through post css. https://github.com/rcaferati/react-awesome-slider Following the ...

Execute CSS within jQuery code only when the body class is present

I am attempting to use CSS (display: none;) within a script to hide elements from my menu only if a specific language is active. When the body class changes from one language to another, I want the script to check if the body class of a certain language ...

I am puzzled as to why it is searching for an ID rather than a view

Currently, I am attempting to navigate to a specific route that includes a form, but for some unknown reason, it is searching for an id. Allow me to provide you with my routes, views, and the encountered error. //celebrities routes const express = requir ...

The arrangement of grid elements does not impact the visual result in CSS

Having issues organizing my HTML into a grid format where the elements are not aligning correctly or moving at all. I am using Firefox and an online server to edit and host the website. Additionally, I am receiving a warning that 'grid-template-area&a ...

My jquery seems to be malfunctioning -- can't quite figure out what the issue is

My jquery is not working as expected! It was functioning fine when I included the script directly in the HTML file, but now that I have moved it to a separate file, it's not working. I even tried changing the file name, but no luck. //HTML file loca ...

Change the background color of the selectInput component in Shiny to fit your

Take a look at this sample shiny app: library(shiny) ui <- fluidPage(tags$head(includeCSS("www/mycss.css")), selectInput("foo", "Choose", width = '20%', multiple = F, selected = "red1", choices = list(red = c ...

Exploring asynchronous data handling in AngularJS using promises

Currently, I am working on a single page application using angularJS and encountering some difficulties in storing asynchronous data. In simple terms, I have a service that contains my data models which are returned as promises (as they can be updated asy ...

The usage of THREE.MeshFaceMaterial has been deprecated and is no longer supported. It is advised to

I'm currently experimenting with wrapping images around a cube in three.js and encountering the error message 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' from my previous research, it seems like the method I am trying to ...

What is the method to enable Google Adsense to reach pages within a restricted login area that utilizes JSON authentication?

I am looking to place Google Adsense ads on my website, but I want them to only appear within a specific area that is accessible to users after they log in. Within the Google Adsense interface, I have explored the Account Settings -> Access and authori ...

Is it possible to use a JavaScript string as a selector in jQuery?

So, my issue is with the following JavaScript code snippet: for ( i=0; i < parseInt(ids); i++){ var vst = '#'+String(img_arr[i]); var dst = '#'+String(div_arr[i]); } I'm wondering how I can proceed in jQuery to handle ...

Is there a way to display the icon in Javascript?

I added a glyphicon element to my page but set its visibility to hidden using CSS. My goal is to reveal the glyphicon (#gl1) when users input text and click the "post" button, but I'm encountering an issue where the glyphicon doesn't show up when ...

I am feeling perplexed by the alert!

function updateDateFormat(){ // alert("hi"); $(".tour-dates ul li").each(function(){ // alert(monthConverter($(this).find(".month").text())); var replace = monthConverter($(this).find(".month").text()); $(this).find(".month").tex ...

What is the best technique to incorporate dark/light mode in Bootstrap 5?

Is it best to introduce themes such as dark and light themes in Bootstrap 5 using CSS/SCSS, JavaScript, or a combination of both? Should we create a separate CSS file like dark.css to overwrite classes? Or should we use JavaScript to switch classes like ...

Having trouble implementing a datetimepicker within a Tabulator column

I am looking to customize the editor for my Tabulator table to handle date values using jQuery DateTimePicker. However, I have encountered issues while trying to modify the example code provided on the Tabulator website. Here is my custom editor code snipp ...

Using Jquery to enhance navigation tabs with pointers

I am facing an issue where the class .hover and .over are added to the entire list whenever I mouseover any list item. I understand that this is happening due to my jQuery code, but I would like to find a way for jQuery to only add the class to the specifi ...

Angular promise objects provide access to important values

let userRequest = $http({ method: 'POST', url: $rootScope.apisrvr + 'user/user_signin', data: { username: $scope.user.username, password: $scope.user.password }, ...

Adjust the dimensions of the Bootstrap 4 navbar overlay to perfectly fit the navigation contents

Looking to customize the width of the Bootstrap 4 navbar overlay? Want it to adapt to its contents instead of occupying the entire screen when activated by clicking the hamburger icon. I've gone through the navbar, navbar-collapse, and navbar-nav clas ...

Effectively encoding and decoding AJAX and JSON objects with PHP scripting

I've successfully set up a basic HTML file with a fixed JSON object. My goal is to transfer this object to a PHP file named text.php, encode it, decode it, display it in the PHP file, and then showcase it back in the HTML file. <!DOCTYPE html> ...

Enhancing the content of a field - React

Seeking assistance with populating an input field with a generated password in my React component. Currently, the password is showing as undefined. MainComponent.js - primary React component class MainComponent extends React.Component { state = { p ...

The Protractor tool (node:9208) threw an UnhandledPromiseRejectionWarning due to an ElementNotVisibleError, indicating that the element is not interactable. Despite this

I am attempting to interact with an element using protractor but encountering the following error (node:9208) UnhandledPromiseRejectionWarning: ElementNotVisibleError: element not interactable (Session information: chrome=69.0.3497.92) (Driver informa ...