Adjust Bootstrap's color scheme dynamically with JavaScript

I need to update certain bootstrap variable values using JavaScript instead of using SCSS. The specific requirement is that the changes must occur on click events, which is why I am opting for JavaScript.

Although I have attempted to implement the code below, it does not work as expected. The console message displays correctly, but the UI colors remain unchanged.

<button type="button" class="btn btn-primary" onclick="UpdateColor()">CHANGE COLOR ON CLICK</button>
<h3 class="text-primary">WHEN BUTTON IS CLICKED MY COLOR SHOULD CHANGE</h3>

<script>
    function UpdateColor() {
        var root = document.querySelector(':root');
        var rs = getComputedStyle(root);

        console.log('before', rs.getPropertyValue('--primary'));
        root.style.setProperty('--primary', 'red');
        console.log('after', rs.getPropertyValue('--primary'));
    }
</script>

Answer №1

It appears you are not utilizing CSS variables...

To implement CSS variables, include the following "style" tag:

<style>
  .text-primary {
    color: var(--primary);
  }
</style>

Here is the expected result:

<button type="button" class="btn btn-primary" onclick="UpdateColor()">CHANGE COLOR ON CLICK</button>
<h3 class="text-primary">WHEN BUTTON IS CLICKED MY COLOR SHOULD CHANGE</h3>
<style>
  .text-primary {
    color: var(--primary);
  }
</style>
<script>
  function UpdateColor() {
    var root = document.querySelector(':root');
    var rs = getComputedStyle(root);

    console.log('before', rs.getPropertyValue('--primary'));
    root.style.setProperty('--primary', 'red');
    console.log('after', rs.getPropertyValue('--primary'));
  }
</script>

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

Experience the seamless integration of Restful APIs with AngularJS and Querystring parameters

I am currently in the process of developing a web application that includes edit functionality. Currently, I have created a page with a list of records, each containing an ID. When I click on the edit button, it triggers the following: $state.go ...

Making the toggle button functional on the navbar

Trying to customize my navbar for tablet and mobile devices is proving to be a challenge. I am looking for a way to make the dropdown button take up the entire page when clicked on. It seems like JavaScript might be the solution, but I'm not quite sur ...

Traversing a hierarchical JSON structure reminiscent of a tree object

I am working with a complex object structure, var cObj = { name: 'Object1', oNumbers: 3, leaf: [ { name: 'Inner Object 1', oNumbers: 4, leaf: [] }, { name: 'Inner Object 2', oN ...

Exploring the Concept of Template Element Recursion in Angular JS 2

In my Angular 2 project, I encountered a situation where I needed to iterate through ngFor based on child elements. My component should be able to render a list based on the input provided. Here is an example of the data structure: [ { name: 'ABC ...

Decode PDF417 barcode images with ease using HTML and JavaScript on both desktop and mobile web browsers

Looking to utilize JavaScript to decode PDF417 type barcode images? If you're encountering Zxing plugin issues in mobile browsers but it works well on desktop browsers with https://github.com/PeculiarVentures/js-zxing-pdf417, consider alternative sol ...

The Typescript const assertion translated into Javascript

Is there a way in JavaScript to achieve constant-like behavior similar to TypeScript's const assertion? const arr = [1,2,3,4] as const I am looking for a solution in JavaScript that allows me to create an array that cannot be further mutated. ...

Are there any downsides to utilizing the jQuery Load function?

I am in the process of creating a website that displays sensor data. I plan to incorporate a HighChart line chart to showcase this data. Since my website is relatively simple in terms of content, I have decided to consolidate all elements onto one page inc ...

Error message: The specified file or directory named '-stylus' could not be found

Encountered an error message while using stylus with npm on my Linux machine. After installing nodejs from GitHub, I executed the command npm install -g stylus autoprefixer-stylus and received the following error log: npm ERR! Error: EACCES, unlink ' ...

The functionality of the web application is not supported in Multi-Device-Hybrid-Apps format

I am encountering an issue with my app that functions perfectly as a typical web app, but fails to work properly when converted into a Multi-Device-Hybrid-App format. The problematic sections are indicated in a screenshot of the app. Below is my complete c ...

Guide on converting a complex nested json into the jquery autocomplete format

How can I properly format a complex nested JSON for use with jQuery autocomplete? I have been attempting to map my custom JSON data to fit the required jQuery autocomplete format of label and value, but unfortunately, my list is returning as 'undefine ...

Utilize JavaScript to extract content from a text file and showcase it in a Bootstrap modal pop-up through knockout binding

I'm currently working on a function that reads data from a .txt file (located in the website's root directory) and then displays it in a modal dialog box. I believe I've made progress as the file is recognized during debugging, but unfortuna ...

Error message: Attempting to access a property that is undefined (specifically 'ref') in MUI

Has anyone encountered this error when trying to customize themes in MUI v5 using custom variants? I keep seeing this error message: https://i.sstatic.net/D7F0e.png TypeError: Cannot read properties of undefined (reading 'ref') at Select (/va ...

Issue with Google Map Info Windows resizing automatically, no changes have been made to the code

Take a look at my map application. By clicking multiple times on a red marker, you will notice that the info window changes size until it becomes unusually large, affecting all other windows as well. Interestingly, previous versions of my code from 1 month ...

Calculating the height of the browser menubar, toolbar, navigation bar, and bookmarks can be easily achieved using jQuery or JavaScript

How can I use jQuery to calculate the height of the browser and adjust the position of another div element accordingly? What steps do I need to take to achieve this functionality? ...

Switch the image displayed on hover over an image using the #map attribute

Recently, I successfully integrated a database connection into this website and made it dynamic. The overall design of the site was already in place, so my main focus was on adding the functionality of the database connection. However, after implementing ...

Exploring the analysis of JavaScript and CSS coverage throughout various pages or websites

The Chrome Dev Tools JavaScript and CSS Coverage Drawer is quite impressive, but there is one thing that could make it even better. It would be great if it could remain active without restarting its analysis every time you visit a new page. I wish I could ...

Having trouble using a setTimeout() callback to display a Bootstrap Vue modal programmatically

I am currently working on a Vue CLI application (using the Webpack template) that utilizes Bootstrap Vue for displaying modal windows. In my Vue component's mounted() hook, I am attempting to programmatically show the modal by referencing the Bootstra ...

Comparison of various approaches for invoking JavaScript/jQuery functions

Do the following examples have a performance variation? Example 1: $(window).on('resize', abc); function abc(){ //some abc code } Example 2: $(window).on('resize', function(){ //some abc code }); If so, what are the positives ...

Unwrapping nested objects in a JSON array with JavaScript: A step-by-step guide

After trying some code to flatten a JSON, I found that it flattened the entire object. However, my specific requirement is to only flatten the position property. Here is the JSON array I am working with: [{ amount:"1 teine med 110 mtr iletau" comment:"" ...

I seem to be having trouble locating the correct file location

Apologies for the simplicity of my question. I've been struggling to include the find.js file in my articles.js file. Despite trying multiple variations, I can't seem to get the pathname right and haven't found a solution online. Can someon ...