Having trouble changing the style property of the `<div>` element in my JS function within Bootstrap Studio

I am currently utilizing Bootstrap in Bootstrap Studio along with plain JavaScript. One of the challenges I am facing pertains to changing the background color of a <div> element upon selecting a new tab.

The objective is to dynamically alter the background colors of tabs and their associated content. For instance, when switching between tab 1 and tab 2, tab 1 should display a blue background while tab 2 should showcase an orange background. The color change should occur seamlessly as tabs are switched. I have defined the base color by adjusting the parent <div> background. (The reason for not explicitly coloring the tab content and active tab is due to the limited size of the colored area).

Below is the current JavaScript function that I have implemented.

window.addEventListener('load', startup);
async function startup(){
    // other functions 
    await toggleColor();
}
async function toggleColor(){
    var menuItem = document.getElementsByName('tabGroup').forEach(item =>{
        item.addEventListener('click', event=>{
            var bg = document.getElementById('tabDiv');
            var bgColor = bg.style.background;
            console.log("Old Color: "+bgColor);
            bgColor = 'linear-gradient(to bottom right, #ec7429, #843f1d)'; 
            console.log("New Color: "+bgColor);
                
        })
    });
}

Below is the CSS styling for both the parent <div id='tabDiv'> and the active tab.

#tabDiv {
    background: linear-gradient(to bottom right, #8c3a83, #682b61); 
}
#tabList .nav-link.active {
  color: #E7E8E9; 
  background: linear-gradient(to bottom right, #8c3a83, #682b61); 
}

Outlined below is the general HTML structure of my project.

<div id='tabDiv'>
    <ul id='tabList' class='nav nav-tabs flex-column' role='tablist'>
         <li id='tabID' class='nav-item' role='presentation' name='tabGroup'>
            <a class='nav-link' role='tab' data-toggle='tab' href='#tab-1'> TabText </a>
        </li>
    </ul>
    <div class='tab-content'>
        <div id='tab-1' class='tab-pane' role='tabpanel'>
            <p> Tab Content <p>
        </div>
    </div>
</div>

Upon running the code in its current state, the console output is as follows:

Old Color:                                  
New Color: linear-gradient(to bottom right, #ec7429, #843f1d)       
Old Color: 
New Color: linear-gradient(to bottom right, #ec7429, #843f1d)

Consequently, I transferred the initial CSS styling to the HTML

<div id='tabDiv' style="background: linear-gradient(144deg, #8c3a83, #682b61);">
. Bootstrap Studio generated this new inline style format.

When executing the code with the styling defined in the HTML rather than the CSS files, the following results were obtained:

Old Color: linear-gradient(144deg, rgb(140, 58, 131), rgb(104, 43, 97))
New Color: linear-gradient(to bottom right, #ec7429, #843f1d)
Old Color: linear-gradient(144deg, rgb(140, 58, 131), rgb(104, 43, 97))
New Color: linear-gradient(to bottom right, #ec7429, #843f1d)

Various attempts were made to modify the formatting and color type (hex or RGB) within the HTML style declaration and the JS function when setting the new color. However, the issue persists with the old color not updating or changing during the JS function. The addition of !important to the new color in JS was also attempted.

There is speculation that the problem may stem from the rendering order. Given my limited experience with Bootstrap Studio, I've sought advice here. I am aware that file order can be adjusted by managing file-type order, but is there a method to alter the CSS vs. JS order? Though I'm uncertain if this is the root cause as another function in my project successfully updates the style.display from 'none' to 'block'.

Similar queries on StackOverflow revolve around correctly retrieving the element and wrapping the function in a window.onload. From what I can discern, both actions have been appropriately implemented in my project. A

window.addEventListener('load', function);
call exists at the commencement of my JS files, and other functions included in that sequence function correctly. Logging to the console has indicated that the tabs I am listening for events on are selected accurately, as well as the <div id='tabDiv'> that I aim to adjust the property of. Experimentation was also conducted with no default color, and the addition of new colors within the JS function.

Could the issue be tied to the code or logical structure? Any guidance would be highly valued. Thank you for taking the time to review this extensive query.

tl;dr: Seeking to modify the styling of an HTML element using a JS function, however, the color fails to update. Despite sounding like a fundamental issue, an effective resolution has not yet been uncovered.

Answer №1

First and foremost, when you need to apply an attribute (such as the background color as inline style), you can utilize the setAttribute method.

Furthermore, the reason you received an empty value for Old color when logging to the console is because bg.style.background is specifically searching for an inline style attribute. If you intend to utilize a CSS external file, you should employ the getComputedStyle method within your script.

Therefore:

item.addEventListener('click', event=> { 
  var bg = document.getElementById('tabDiv');
  var bgColor = bg.style.background; // works with inline-style
  var bgColor2 = bg.getPropertyValue('background'); // works with stylesheet
  console.log("Inline Color: "+bgColor + "Stylesheet Color: "+bgColor2);
  bgColor = 'linear-gradient(to bottom right, #ec7429, #843f1d)'; // does not set any property to the element, only assigns a value to a variable.
bg.setAttribute('style', 'background:' + bgColor); // applies inline style to the element with the color from the variable above.
  console.log("New Color: "+bgColor);
})

Answer №2

Big shoutout to @a-meshu for the amazing assistance! Below you can find the updated version of my JavaScript function.

 async function changeBackground(){
    var tabs = document.getElementsByName('tabLeft').forEach(tab =>{
        tab.addEventListener('click', event=>{
            var bgDiv = document.getElementById('tabDiv');
            var computedBgColor =  window.getComputedStyle(bgDiv);
            bgDiv.setAttribute('style', 'background: linear-gradient(to bottom right, #ec7429, #843f1d)');
            console.log("Updated Color: "+ computedBgColor);
                
        })
    });
} 

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

Guide to displaying a confirmation prompt in c# programming

I need to create a confirmation window similar to confirm() in JavaScript that will pop up when a button is clicked. If the user selects "YES", I want to execute some C# code. How can I achieve this? EDIT: here is the code snippet that I have: SCRIPT: & ...

Tips for maintaining the current route in Vue.js after a page refresh while running the Vue.js project in development mode on a specific port?

In my router.ts file, I have defined two routes: export default new Router({ mode: "history", routes: [ { path: "/", component: require("./components/dashboard/Dashboard.vue")}, { path: "/counter", component: require("./components/ ...

When using JSON.Stringify in a React App, it only displays the first item and the length of the object instead of all the other items

Working on a React App, I encountered an issue while trying to convert an array to JSON and send it to the server. My approach was like this: console.log(JSON.stringify(mainArray)) I anticipated seeing output like this during testing: "breakfast": { ...

Having trouble selecting a button using xpath in Scrapy Python?

I am currently attempting to scrape quotes from a website called using my spider code that looks something like this: class quote(scrapy.Spider): name = 'quotes' # defining Name start_urls = [''] # Targeted urls def parse(s ...

How come child elements are clipped in IE versions 9 and above when using the border-radius property with a fixed value?

When applying css border-radius:[some value] to a parent element and having a fixed positioned child element, I noticed that in Internet Explorer the child element appears to be 'clipped' into the parent. However, if I use border-radius:0 in the ...

ASP.NET Core does not support jQuery.validate functionality

After successfully creating a functional jQuery.validation form using HTML, CSS, and JS with dependencies like jQuery and Validation, I encountered an issue when implementing the same code in a clean ASP.NET Core web project. It seems that my custom valida ...

WebPack bundling causing issues with Knockout Validation

I am developing a web application using Knockout along with the Knockout-Validation plugin, and I want to utilize WebPack for bundling. However, I encountered an issue where Knockout-Validation seems to break when incorporated with WebPack. To illustrate ...

The appearance of a list item (<li>) changes when navigating to a different page within a master page

I encountered an issue where after logging in with a username and password, upon being redirected to the homepage, the login button reappears on all pages instead of remaining hidden until I logout. My goal is for the login button within the <ul> ele ...

Exploring the Features of PrimeNG Table Component in Angular 8

After attempting to implement p-table (PrimeNG table) in my Angular project and importing all necessary dependencies and modules using the CLI, I encountered the following error: ERROR: The target entry-point "primeng/table" has missing dependencies: - @ ...

How can I pass the value of a variable from one Vue.js 2 component to another?

Here is how I have structured my view: <div class="row"> <div class="col-md-3"> <search-filter-view ...></search-filter-view> </div> <div class="col-md-9"> <search-result-view ...></ ...

retain the input data from the form by using the keyup event

Currently, I have a scenario where an input field is used to capture user input. Instead of displaying the entered value directly, I am looking to store it in a variable and subsequently use it to retrieve data from a database. Below is the code snippet I ...

MUI version 5 - Checkboxes are receiving a variety of unique classes

After recently upgrading from Mui v4 to v5, I've noticed a strange behavior with checkboxes. Upon inspecting the DOM differences between the two versions, it appears that some additional classes are now being applied in v5 and the extra span with the ...

Choose an identifier from a CSS class

I've been experimenting with a code pen that I stumbled upon: http://codepen.io/surjithctly/pen/pLDwe When I encase the checkbox in a div with the class "mynav," it stops functioning as intended. How do I implement the specified styling for the check ...

Sort through the array using a separate array in Vuejs

I am currently working with two arrays: { "products": [ { "name": "Jivi", "Hint": "45-60 IE/kg alle 5 Tage\n60 IE 1x/Woche\n30-40 IE 2 x/Woche", "frequency": ["1", "2", "8"] }, { "name": "Adynovi", ...

What is causing the default switch to constantly loop in repetition?

Currently, I am working on a Discord bot using discord.js and utilizing a switch statement. However, I am encountering an issue where the "default:" case keeps repeating itself every time any other case is executed. I have already investigated for cases w ...

When using classList.replace, it should swap out every instance of the class xxx1yyy with xx

I attempted to swap a class and came across this helpful example here: javascript: replace classList that is inside a conditional Unfortunately, my attempt at modification (shown below) did not work. The use of classList.replace should change all instanc ...

What are the best methods for aligning pseudo elements vertically?

I am facing an issue with the placement of a before and after pseudo element for articleSubTitle. The problem occurs when the text from articleSubTitle wraps to a new line within a small container or on mobile devices. This causes the after element to appe ...

Tips for preventing tiny separation lines from appearing above and below unordered list elements

I am attempting to utilize twitter bootstrap to create a select-option style list. How can I eliminate the thin separation lines above and below the list of items? Refer to the screenshot: https://i.sstatic.net/1khEE.png Below is the visible code snippe ...

The sidebar I designed didn't completely extend across the column in Bootstrap

My sidebar in Bootstrap didn't fill the entire column because I forgot to set a specific width for it. Here is the CSS code for my sidebar: .sidebar { position: fixed; /* top: 0; bottom: 0; left: ...

Getting an error that reads, "Unable to read properties of null (reading 'uid')," but surprisingly, the application continues to function properly

After logging out, I encounter the following error: (Uncaught TypeError: Cannot read properties of null (reading 'uid')). However, my application functions as intended. During the logout process, I delete an API access token from the user docume ...