2

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; 
}
2
  • Why not reverse it and set the colors from javascript? Commented Nov 28, 2016 at 13:33
  • @Bálint because these are the main colors for the entire site. Commented Nov 28, 2016 at 13:34

1 Answer 1

2

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])})
}
Sign up to request clarification or add additional context in comments.

1 Comment

I tweaked your solution a bit because I like names more than indices, so ended up using a dictionary instead of a list: colorValues[colors[i]] = bodyStyles.getPropertyValue(colors[i]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.