Access the current theme colors of Bootstrap using JavaScript

My goal is to generate charts with chart.js using colors that align with the chosen Bootstrap 4 theme (which has several options available for the site).

My approach at the moment involves having a badge of each color displayed on the page:

  <div id="color-example-badge-primary" class="badge badge-primary" ></div >
  <div id="color-example-badge-warning" class="badge badge-warning" ></div >
  <div id="color-example-badge-danger" class="badge badge-danger" ></div >
  <div id="color-example-badge-secondary" class="badge badge-secondary" ></div >
  <div id="color-example-badge-light" class="badge badge-light" ></div >
  <div id="color-example-badge-success" class="badge badge-success" ></div >
  <div id="color-example-badge-info" class="badge badge-info" ></div >
  <div id="color-example-badge-dark" class="badge badge-dark" ></div >

I then use jQuery to extract the background colors into an array:

var themeColors = [$("#color-example-badge-primary").css('backgroundColor'),
                   $("#color-example-badge-warning").css('backgroundColor'),
                   $("#color-example-badge-danger").css('backgroundColor'),
                   $("#color-example-badge-secondary").css('backgroundColor'),
                   $("#color-example-badge-light").css('backgroundColor'),
                   $("#color-example-badge-success").css('backgroundColor'),
                   $("#color-example-badge-info").css('backgroundColor'),
                   $("#color-example-badge-dark").css('backgroundColor')
];

This array can be passed to chart.js to create a chart with the theme's colors.

Is there a more efficient way to retrieve the current theme colors from the CSS using JavaScript? Or is it necessary to create a DOM element and check its background color?

If there is a simpler method to access CSS properties using JavaScript without involving a DOM element, I would love to know about it.

Answer №1

Bootstrap's themed colors are stored within CSS variables on the :root element.

A more efficient method involves extracting these colors using getComputedStyle() and getPropertyValue('--variable')

const style = getComputedStyle(document.body);
const theme = {
  primary: style.getPropertyValue('--primary'),
  secondary: style.getPropertyValue('--secondary'),
  success: style.getPropertyValue('--success'),
  info: style.getPropertyValue('--info'),
  warning: style.getPropertyValue('--warning'),
  danger: style.getPropertyValue('--danger'),
  light: style.getPropertyValue('--light'),
  dark: style.getPropertyValue('--dark'),
};

console.log(theme);
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<div class="container"></div>

Now you can utilize these colors in your projects with JavaScript or jQuery as shown below

element.style.backgroundColor = theme.primary; // JavaScript
$(element).css('background-color', theme.primary); // jQuery

For Bootstrap 5

In Bootstrap 5, these properties have been renamed. To adapt the above code for use with Bootstrap 5, refer to the example below

const style = getComputedStyle(document.body);
const theme = {
  primary: style.getPropertyValue('--bs-primary'),
  secondary: style.getPropertyValue('--bs-secondary'),
  success: style.getPropertyValue('--bs-success'),
  info: style.getPropertyValue('--bs-info'),
  warning: style.getPropertyValue('--bs-warning'),
  danger: style.getPropertyValue('--bs-danger'),
  light: style.getPropertyValue('--bs-light'),
  dark: style.getPropertyValue('--bs-dark'),
};

console.log(theme);
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93f1fcfce7e0e7e1f2e3d3a6bda1bda3">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="21434e4e55525553405161140f130f11">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">

<div class="container"></div>

Answer №2

Utilize the code

document.body.getElementsByTagName("*")
to extract all elements within the body tag and iterate through them to obtain desired information.

    $(document).ready(function(){
    var items = document.body.getElementsByTagName("*");
    var arr=[];

    for (var i = 4, len = items.length; i < len; i++) {
    arr.push(document.getElementById(items[i].id)!=null?$('#'+items[i].id).css('backgroundColor'):"");

    }
    console.log(arr)
    });
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
      
    <div id="color-example-badge-primary" class="badge badge-primary" >a</div >
      <div id="color-example-badge-warning" class="badge badge-warning" >a</div >
      <div id="color-example-badge-danger" class="badge badge-danger" >a</div >
      <div id="color-example-badge-secondary" class="badge badge-secondary" >a</div >
      <div id="color-example-badge-light" class="badge badge-light" >a</div >
      <div id="color-example-badge-success" class="badge badge-success" >a</div >
      <div id="color-example-badge-info" class="badge badge-info" >a</div >
      <div id="color-example-badge-dark" class="badge badge-dark" >a</div >

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

The middleware function encountered an undefined value in req.body

I've been attempting to validate my data retrieved from my express endpoint using yup. Despite watching numerous tutorials, I am encountering a particular error that has me stuck. Every time I try to validate the data in my middleware, it consistentl ...

Generate a dot density map with the help of Google Maps

I am looking to create a dot density map using Google Maps for my state. I have all the counties outlined with their respective populations, and I want to scatter dots randomly within each county to represent the population. The goal is to make a dot densi ...

Stop access to geojson files through targeted media queries

Using a vue.js app, I have the ability to choose locations using either a map or an input field. However, for mobile users, I want to exclude the map and only serve the search engine. The issue is that it's not very user-friendly on mobile devices be ...

Creating a basic bootstrap modal dialog in ASP.NET MVC: A step-by-step guide

After navigating from the login page, the user clicks on the "ForgotPassword" link and is directed to a separate page where they can fill out a form to request a new password. http://localhost:2350/Account/ForgotPassword Once the user clicks on the "Save ...

The overflow-x property is failing to hide content in Safari

My website functions perfectly on all browsers except Safari. When using Safari, I'm able to scroll horizontally for an excessive amount of pixels. Has anyone experienced this issue before? ...

Translating Javascript to Coffeescript

Initially, I had a piece of javascript code that functioned properly on its own. function update_checkboxes() { var part_array = []; $("input#edit:checked").parents('td').next().each(function(){ part_id = $(this). ...

The component 'createSvgIcon' from 'material-ui' is not available in the 'utils' module of '@material-ui/core'

After installing material-ui/lab to utilize the alert component, I encountered an issue when trying to import it using import Alert from '@material-ui/lab/Alert';. It failed to compile and threw the following error: ./node_modules/@material-ui/l ...

JavaScript is having difficulty retrieving the property value

Whenever I click a checkbox, I encounter the error "Unable to get the value of the property 'checked'. object is null or undefined." The form I am working with has the name 'test', and my objective is to display additional input fields ...

How to maintain the side padding of a table within a Bootstrap 4 card?

JSFiddle: Click Here In my design, I have a table within a card element. However, when the window size is reduced to mimic a mobile device, the left padding remains intact while the right padding disappears. How can I ensure that the right side padding is ...

Angular-cli: The launch speed needs improvement

Looking for ways to speed up the launch time of my Angular2 application. Currently, it takes 10-12 seconds to load. The application has multiple modules that are loaded using lazy loading. Here is a snippet from my package.json file: { // Package deta ...

Sending all received parameters in a single request in Grails

In my Grails application, I am using the following JavaScript function: function sendPostRequest() { var projectNameFilter = $("input[name='project-name-filter']").val(); var addressFilter = $("input[name='address-filter&apo ...

The outcome of calling jQuery's attr('id') method may result in an undefined value

When a user clicks on an item from a list, it is assigned the 'active-child' class. Only one item can be selected at a time, and when a new item is clicked, the previously selected item loses the 'active-child' class which then gets add ...

Utilizing asynchronous operations in MongoDB with the help of Express

Creating a mobile application utilizing MongoDB and express.js with the Node.js MongoDB driver (opting for this driver over Mongoose for enhanced performance). I am aiming to incorporate asynchronous functions as a more sophisticated solution for handling ...

Could you explain the distinction between addClass and attr functions in jQuery?

When it comes to adding a class, we have two options at our disposal. $('#x').addClass('test'); Alternatively, we can achieve the same result using the following method: $('#x').attr('class','test'); Th ...

Utilize CSS to break apart text (text = white space = text) and align text in a floating manner, allowing

Is there a way to use CSS to create a white space in the middle of text? Currently, I am manually breaking the text, which is not ideal. I am aware that there is a function that allows the text to end and start in another div, but unfortunately, it is not ...

Limit input in jQuery autocomplete to only accept selections from dropdown menu options

Hello, I am seeking assistance with implementing an autocomplete feature in my code that restricts input to values within a specified data array. Only the elements within this array should be allowed as valid inputs. For instance, if a user types "iran01," ...

How can I display an array of data with a changing name using a FlatList in React Native?

How can I render a list of array data with a dynamic name in a FlatList using React Native? Below is the list of data that I would like to display in the FlatList: const movies = [ { '4W2JJ0CLbvfLJzBUHORVaz6sAGv2': [ { name: ...

Ways to add elements to a non-existent index in an array

I am facing an issue while attempting to form sets of objects in an array and generating a new set if the item is not already present. The structure of the data looks something like this: [ { "order": orderData, "items": itemData }, { "or ...

Encode JavaScript Array to URL - converting an array into an object

I have an array structured like this: { search: "job", keywords: "", cat: [12,28,38] } and I am seeking a URL string in this format: ?search=job&keywords=&cat%5B%5D=12&cat%5B%5D=28&cat%5B%5D=38 to use for my query in WordPress. Pleas ...

Guide on retrieving HTML content from a URL and showing it in a div

I'm trying to retrieve the content of a URL and display it within a DIV element, but I'm struggling to achieve the desired result. Below is the code I'm using: index.js fetch('https://github.com/') .then(res => res.text()) ...