i-love-euclides i-love-euclides - 10 days ago 6
Javascript Question

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;
}

Answer

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 colors = ['--maincolor', '--secondcolor', '--thirdcolor', '--fourthcolor'];
var colorValues = [];

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