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.