Celebrian
Celebrian

Reputation: 430

Pass colors from CSS to Javascript

I am defining my theme colors as variables in my CSS file. Then I want to use the same colors in my JavaScript (it takes values from a database and generates graphs). I do not want to specify the colors again in the JS. Can I load a list of colors from the CSS, and if so, how?

CSS file:

/* http://www.colorhunt.co/c/43601 */
:root{
    --maincolor: #113f67;
    --secondcolor: #34699a;
    --thirdcolor: #408ab4;
    --fourthcolor: #65c6c4; 
}

Upvotes: 2

Views: 342

Answers (1)

roberrrt-s
roberrrt-s

Reputation: 8210

Apply the variables to the body, then read out the styles using getComputedStyle

var bodyStyles = window.getComputedStyle(document.body);

This returns an object of all styles defined on the body, now you can retrace it using getPropertyValue

var varName = bodyStyles.getPropertyValue('--var-name');

In which varName now contains your variable, to do this for all colors:

var bodyStyles = window.getComputedStyle(document.body);
var colors = ['--maincolor', '--secondcolor', '--thirdcolor', '--fourthcolor'];
var colorValues = [];

for (var i = 0; i < colors.length; i++) {
    colorValues.push({'name': colors[i], 'hex': bodyStyles.getPropertyValue(colors[i])})
}

Upvotes: 2

Related Questions