How do I edit a CSS variable using JS?
up vote
22
down vote
favorite
I have these CSS variables to control the colors of my project so I can do theming.
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
However no matter how I try to change the attribute(the two commented lines tried separately), the closest I get is returning not a valid attribute.
function loadTheme() {
var htmlTag = document.getElementsByTagName("html");
var yourSelect = document.getElementById( "themeSelect" );
var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value );
// htmlTag[0].setAttribute('--main-text-color', '#FFCF40');
// $("html").css("--main-text-color","#FFCF40");
}
javascript jquery css
|
show 2 more comments
up vote
22
down vote
favorite
I have these CSS variables to control the colors of my project so I can do theming.
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
However no matter how I try to change the attribute(the two commented lines tried separately), the closest I get is returning not a valid attribute.
function loadTheme() {
var htmlTag = document.getElementsByTagName("html");
var yourSelect = document.getElementById( "themeSelect" );
var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value );
// htmlTag[0].setAttribute('--main-text-color', '#FFCF40');
// $("html").css("--main-text-color","#FFCF40");
}
javascript jquery css
I don't recall--main-text-color
being a valid CSS attribute. Is that using a a pre-processor?
– ochi
Dec 28 '16 at 22:43
No it is a css variable. I found out about them in this article
– David Richards
Dec 28 '16 at 22:44
broken-links.com/2014/08/28/…
– David Richards
Dec 28 '16 at 22:44
2
Yes, those CSS variables use a 'native' pre-processor (basically, they eventually get converted into the real property/attribute beforehand). BTW, this feature is not widely supported by all browsers (only FF, from the article. I dunno about other browsers) - in any case, your syntax is incorrect if you want to manipulate them in JS. You need to manipulate properties (not attributes, it seems) - so tryhtmlTag[0].styles.setProperty('--main-text-color', '#FFCF40');
– ochi
Dec 28 '16 at 22:54
I copied your answer in and now the error is that it can not set property of undefined. Could I bother you for a fiddle example?
– David Richards
Dec 28 '16 at 23:12
|
show 2 more comments
up vote
22
down vote
favorite
up vote
22
down vote
favorite
I have these CSS variables to control the colors of my project so I can do theming.
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
However no matter how I try to change the attribute(the two commented lines tried separately), the closest I get is returning not a valid attribute.
function loadTheme() {
var htmlTag = document.getElementsByTagName("html");
var yourSelect = document.getElementById( "themeSelect" );
var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value );
// htmlTag[0].setAttribute('--main-text-color', '#FFCF40');
// $("html").css("--main-text-color","#FFCF40");
}
javascript jquery css
I have these CSS variables to control the colors of my project so I can do theming.
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
However no matter how I try to change the attribute(the two commented lines tried separately), the closest I get is returning not a valid attribute.
function loadTheme() {
var htmlTag = document.getElementsByTagName("html");
var yourSelect = document.getElementById( "themeSelect" );
var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value );
// htmlTag[0].setAttribute('--main-text-color', '#FFCF40');
// $("html").css("--main-text-color","#FFCF40");
}
javascript jquery css
javascript jquery css
edited Dec 28 '16 at 23:22
Brett DeWoody
28.8k1885127
28.8k1885127
asked Dec 28 '16 at 22:40
David Richards
140137
140137
I don't recall--main-text-color
being a valid CSS attribute. Is that using a a pre-processor?
– ochi
Dec 28 '16 at 22:43
No it is a css variable. I found out about them in this article
– David Richards
Dec 28 '16 at 22:44
broken-links.com/2014/08/28/…
– David Richards
Dec 28 '16 at 22:44
2
Yes, those CSS variables use a 'native' pre-processor (basically, they eventually get converted into the real property/attribute beforehand). BTW, this feature is not widely supported by all browsers (only FF, from the article. I dunno about other browsers) - in any case, your syntax is incorrect if you want to manipulate them in JS. You need to manipulate properties (not attributes, it seems) - so tryhtmlTag[0].styles.setProperty('--main-text-color', '#FFCF40');
– ochi
Dec 28 '16 at 22:54
I copied your answer in and now the error is that it can not set property of undefined. Could I bother you for a fiddle example?
– David Richards
Dec 28 '16 at 23:12
|
show 2 more comments
I don't recall--main-text-color
being a valid CSS attribute. Is that using a a pre-processor?
– ochi
Dec 28 '16 at 22:43
No it is a css variable. I found out about them in this article
– David Richards
Dec 28 '16 at 22:44
broken-links.com/2014/08/28/…
– David Richards
Dec 28 '16 at 22:44
2
Yes, those CSS variables use a 'native' pre-processor (basically, they eventually get converted into the real property/attribute beforehand). BTW, this feature is not widely supported by all browsers (only FF, from the article. I dunno about other browsers) - in any case, your syntax is incorrect if you want to manipulate them in JS. You need to manipulate properties (not attributes, it seems) - so tryhtmlTag[0].styles.setProperty('--main-text-color', '#FFCF40');
– ochi
Dec 28 '16 at 22:54
I copied your answer in and now the error is that it can not set property of undefined. Could I bother you for a fiddle example?
– David Richards
Dec 28 '16 at 23:12
I don't recall
--main-text-color
being a valid CSS attribute. Is that using a a pre-processor?– ochi
Dec 28 '16 at 22:43
I don't recall
--main-text-color
being a valid CSS attribute. Is that using a a pre-processor?– ochi
Dec 28 '16 at 22:43
No it is a css variable. I found out about them in this article
– David Richards
Dec 28 '16 at 22:44
No it is a css variable. I found out about them in this article
– David Richards
Dec 28 '16 at 22:44
broken-links.com/2014/08/28/…
– David Richards
Dec 28 '16 at 22:44
broken-links.com/2014/08/28/…
– David Richards
Dec 28 '16 at 22:44
2
2
Yes, those CSS variables use a 'native' pre-processor (basically, they eventually get converted into the real property/attribute beforehand). BTW, this feature is not widely supported by all browsers (only FF, from the article. I dunno about other browsers) - in any case, your syntax is incorrect if you want to manipulate them in JS. You need to manipulate properties (not attributes, it seems) - so try
htmlTag[0].styles.setProperty('--main-text-color', '#FFCF40');
– ochi
Dec 28 '16 at 22:54
Yes, those CSS variables use a 'native' pre-processor (basically, they eventually get converted into the real property/attribute beforehand). BTW, this feature is not widely supported by all browsers (only FF, from the article. I dunno about other browsers) - in any case, your syntax is incorrect if you want to manipulate them in JS. You need to manipulate properties (not attributes, it seems) - so try
htmlTag[0].styles.setProperty('--main-text-color', '#FFCF40');
– ochi
Dec 28 '16 at 22:54
I copied your answer in and now the error is that it can not set property of undefined. Could I bother you for a fiddle example?
– David Richards
Dec 28 '16 at 23:12
I copied your answer in and now the error is that it can not set property of undefined. Could I bother you for a fiddle example?
– David Richards
Dec 28 '16 at 23:12
|
show 2 more comments
6 Answers
6
active
oldest
votes
up vote
16
down vote
accepted
Turns out changing CSS variables is possible using the el.style.cssText
property, or el.style.setProperty
or el.setAttribute
methods. In your code snippets el.setAttribute
is incorrectly used, which is causing the error you encountered. Here's the correct way:
var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";
or
var html = document.getElementsByTagName('html')[0];
html.style.setProperty("--main-background-color", "green");
or
var html = document.getElementsByTagName('html')[0];
html.setAttribute("style", "--main-background-color: green");
Demo
The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.
window.onload = function() {
setTimeout(function() {
var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";
}, 2000);
};
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
body {
background-color: var(--main-background-color);
}
This will only work in browsers supporting CSS variables obviously.
4
This will overwrite the existing inline styles.
– Oriol
Dec 28 '16 at 23:30
yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
– SuperUberDuper
Mar 19 at 22:19
add a comment |
up vote
12
down vote
If you are using :root
:
:root {
--somevar: black;
}
It will be documentElement.
document.documentElement.style.setProperty('--somevar', 'green');
add a comment |
up vote
10
down vote
You can simply use the standard way of setting arbitrary CSS properties: setProperty
document.body.style.setProperty('--background-color', 'blue');
body {
--background-color: red;
background-color: var(--background-color);
}
for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
– SuperUberDuper
Mar 19 at 22:20
add a comment |
up vote
6
down vote
The native solution
The standard methods to get/set CSS3 variables are .setProperty()
and .getPropertyValue()
.
If your Variables are Globals (declared in :root
), you can use the following, for getting and setting their values.
// setter
document.documentElement.style.setProperty('--myVariable', 'blue');
// getter
document.documentElement.style.getPropertyValue('--myVariable');
However the getter will only return the value of a var, if has been set, using .setProperty()
.
If has been set through CSS declaration, will return undefined
. Check it in this example:
let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
<div>Red background set by --myVariable</div>
To avoid that unexpected behavior you have to make use of the getComputedStyle()
method , before calling .getPropertyValue()
.
The getter will then , look lik this :
getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');
In my opinion, accessing CSS variables should be more simple, fast, intuitive and natural...
My personal approach
I've implemented CSSGlobalVariables
a tiny (<3kb) javascript helper wich automatically detects and packs into an Object, all the active CSS global variables in a document, for easier acces & manipulation.
// set a new value to --myVariable
cssVar.myVariable = 'red';
// get the value of --myVariable
console.log( cssVar.myVariable );
Any change applied to the Object properties, is translated automatically to the CSS variables.
Available in : https://github.com/colxi/css-global-variables
add a comment |
up vote
1
down vote
You could add something like below (without using class variables)
function loadTheme() {
var htmlTag = document.getElementById("myDiv");
var yourSelect = document.getElementById("themeSelect");
var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
console.log("selected theme: " + selectedTheme);
// reset class names
htmlTag.className = '';
// add selected theme
htmlTag.className = 'theme' + selectedTheme;
}
.theme1 {
color: blue;
}
.theme2 {
color: red;
}
<div id="myDiv">
test
</div>
<select id="themeSelect" onChange="loadTheme()">
<option value="1">Theme 1</option>
<option value="2">Theme 2</option>
</select>
Downvoted because it doesn't answer the question at all.
– Ced
Jun 3 '17 at 17:34
@Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
– ochi
Jun 3 '17 at 20:11
1
changed my vote
– Ced
Jun 3 '17 at 20:26
add a comment |
up vote
0
down vote
It would probably be easier to define classes in your CSS that contain the various theme styles (.theme1 {...}
, .theme2 {...}
, etc) and then change the class with JS based on the selected value.
2
This is more of a comment than an answer
– ochi
Dec 28 '16 at 23:01
I didn't think about that. I'll give that a shot and get back to you
– David Richards
Dec 28 '16 at 23:10
add a comment |
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
16
down vote
accepted
Turns out changing CSS variables is possible using the el.style.cssText
property, or el.style.setProperty
or el.setAttribute
methods. In your code snippets el.setAttribute
is incorrectly used, which is causing the error you encountered. Here's the correct way:
var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";
or
var html = document.getElementsByTagName('html')[0];
html.style.setProperty("--main-background-color", "green");
or
var html = document.getElementsByTagName('html')[0];
html.setAttribute("style", "--main-background-color: green");
Demo
The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.
window.onload = function() {
setTimeout(function() {
var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";
}, 2000);
};
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
body {
background-color: var(--main-background-color);
}
This will only work in browsers supporting CSS variables obviously.
4
This will overwrite the existing inline styles.
– Oriol
Dec 28 '16 at 23:30
yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
– SuperUberDuper
Mar 19 at 22:19
add a comment |
up vote
16
down vote
accepted
Turns out changing CSS variables is possible using the el.style.cssText
property, or el.style.setProperty
or el.setAttribute
methods. In your code snippets el.setAttribute
is incorrectly used, which is causing the error you encountered. Here's the correct way:
var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";
or
var html = document.getElementsByTagName('html')[0];
html.style.setProperty("--main-background-color", "green");
or
var html = document.getElementsByTagName('html')[0];
html.setAttribute("style", "--main-background-color: green");
Demo
The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.
window.onload = function() {
setTimeout(function() {
var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";
}, 2000);
};
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
body {
background-color: var(--main-background-color);
}
This will only work in browsers supporting CSS variables obviously.
4
This will overwrite the existing inline styles.
– Oriol
Dec 28 '16 at 23:30
yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
– SuperUberDuper
Mar 19 at 22:19
add a comment |
up vote
16
down vote
accepted
up vote
16
down vote
accepted
Turns out changing CSS variables is possible using the el.style.cssText
property, or el.style.setProperty
or el.setAttribute
methods. In your code snippets el.setAttribute
is incorrectly used, which is causing the error you encountered. Here's the correct way:
var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";
or
var html = document.getElementsByTagName('html')[0];
html.style.setProperty("--main-background-color", "green");
or
var html = document.getElementsByTagName('html')[0];
html.setAttribute("style", "--main-background-color: green");
Demo
The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.
window.onload = function() {
setTimeout(function() {
var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";
}, 2000);
};
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
body {
background-color: var(--main-background-color);
}
This will only work in browsers supporting CSS variables obviously.
Turns out changing CSS variables is possible using the el.style.cssText
property, or el.style.setProperty
or el.setAttribute
methods. In your code snippets el.setAttribute
is incorrectly used, which is causing the error you encountered. Here's the correct way:
var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";
or
var html = document.getElementsByTagName('html')[0];
html.style.setProperty("--main-background-color", "green");
or
var html = document.getElementsByTagName('html')[0];
html.setAttribute("style", "--main-background-color: green");
Demo
The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.
window.onload = function() {
setTimeout(function() {
var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";
}, 2000);
};
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
body {
background-color: var(--main-background-color);
}
This will only work in browsers supporting CSS variables obviously.
window.onload = function() {
setTimeout(function() {
var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";
}, 2000);
};
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
body {
background-color: var(--main-background-color);
}
window.onload = function() {
setTimeout(function() {
var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";
}, 2000);
};
html {
--main-background-image: url(../images/starsBackground.jpg);
--main-text-color: #4CAF50;
--main-background-color: rgba(0,0,0,.25);
--beta-background-color: rgba(0,0,0,.85);
}
body {
background-color: var(--main-background-color);
}
edited Jul 27 at 10:51
answered Dec 28 '16 at 23:16
Brett DeWoody
28.8k1885127
28.8k1885127
4
This will overwrite the existing inline styles.
– Oriol
Dec 28 '16 at 23:30
yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
– SuperUberDuper
Mar 19 at 22:19
add a comment |
4
This will overwrite the existing inline styles.
– Oriol
Dec 28 '16 at 23:30
yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
– SuperUberDuper
Mar 19 at 22:19
4
4
This will overwrite the existing inline styles.
– Oriol
Dec 28 '16 at 23:30
This will overwrite the existing inline styles.
– Oriol
Dec 28 '16 at 23:30
yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
– SuperUberDuper
Mar 19 at 22:19
yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
– SuperUberDuper
Mar 19 at 22:19
add a comment |
up vote
12
down vote
If you are using :root
:
:root {
--somevar: black;
}
It will be documentElement.
document.documentElement.style.setProperty('--somevar', 'green');
add a comment |
up vote
12
down vote
If you are using :root
:
:root {
--somevar: black;
}
It will be documentElement.
document.documentElement.style.setProperty('--somevar', 'green');
add a comment |
up vote
12
down vote
up vote
12
down vote
If you are using :root
:
:root {
--somevar: black;
}
It will be documentElement.
document.documentElement.style.setProperty('--somevar', 'green');
If you are using :root
:
:root {
--somevar: black;
}
It will be documentElement.
document.documentElement.style.setProperty('--somevar', 'green');
answered Nov 8 '17 at 6:08
Blauhirn
4,84822964
4,84822964
add a comment |
add a comment |
up vote
10
down vote
You can simply use the standard way of setting arbitrary CSS properties: setProperty
document.body.style.setProperty('--background-color', 'blue');
body {
--background-color: red;
background-color: var(--background-color);
}
for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
– SuperUberDuper
Mar 19 at 22:20
add a comment |
up vote
10
down vote
You can simply use the standard way of setting arbitrary CSS properties: setProperty
document.body.style.setProperty('--background-color', 'blue');
body {
--background-color: red;
background-color: var(--background-color);
}
for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
– SuperUberDuper
Mar 19 at 22:20
add a comment |
up vote
10
down vote
up vote
10
down vote
You can simply use the standard way of setting arbitrary CSS properties: setProperty
document.body.style.setProperty('--background-color', 'blue');
body {
--background-color: red;
background-color: var(--background-color);
}
You can simply use the standard way of setting arbitrary CSS properties: setProperty
document.body.style.setProperty('--background-color', 'blue');
body {
--background-color: red;
background-color: var(--background-color);
}
document.body.style.setProperty('--background-color', 'blue');
body {
--background-color: red;
background-color: var(--background-color);
}
document.body.style.setProperty('--background-color', 'blue');
body {
--background-color: red;
background-color: var(--background-color);
}
answered Dec 28 '16 at 23:27
Oriol
153k33252353
153k33252353
for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
– SuperUberDuper
Mar 19 at 22:20
add a comment |
for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
– SuperUberDuper
Mar 19 at 22:20
for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
– SuperUberDuper
Mar 19 at 22:20
for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
– SuperUberDuper
Mar 19 at 22:20
add a comment |
up vote
6
down vote
The native solution
The standard methods to get/set CSS3 variables are .setProperty()
and .getPropertyValue()
.
If your Variables are Globals (declared in :root
), you can use the following, for getting and setting their values.
// setter
document.documentElement.style.setProperty('--myVariable', 'blue');
// getter
document.documentElement.style.getPropertyValue('--myVariable');
However the getter will only return the value of a var, if has been set, using .setProperty()
.
If has been set through CSS declaration, will return undefined
. Check it in this example:
let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
<div>Red background set by --myVariable</div>
To avoid that unexpected behavior you have to make use of the getComputedStyle()
method , before calling .getPropertyValue()
.
The getter will then , look lik this :
getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');
In my opinion, accessing CSS variables should be more simple, fast, intuitive and natural...
My personal approach
I've implemented CSSGlobalVariables
a tiny (<3kb) javascript helper wich automatically detects and packs into an Object, all the active CSS global variables in a document, for easier acces & manipulation.
// set a new value to --myVariable
cssVar.myVariable = 'red';
// get the value of --myVariable
console.log( cssVar.myVariable );
Any change applied to the Object properties, is translated automatically to the CSS variables.
Available in : https://github.com/colxi/css-global-variables
add a comment |
up vote
6
down vote
The native solution
The standard methods to get/set CSS3 variables are .setProperty()
and .getPropertyValue()
.
If your Variables are Globals (declared in :root
), you can use the following, for getting and setting their values.
// setter
document.documentElement.style.setProperty('--myVariable', 'blue');
// getter
document.documentElement.style.getPropertyValue('--myVariable');
However the getter will only return the value of a var, if has been set, using .setProperty()
.
If has been set through CSS declaration, will return undefined
. Check it in this example:
let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
<div>Red background set by --myVariable</div>
To avoid that unexpected behavior you have to make use of the getComputedStyle()
method , before calling .getPropertyValue()
.
The getter will then , look lik this :
getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');
In my opinion, accessing CSS variables should be more simple, fast, intuitive and natural...
My personal approach
I've implemented CSSGlobalVariables
a tiny (<3kb) javascript helper wich automatically detects and packs into an Object, all the active CSS global variables in a document, for easier acces & manipulation.
// set a new value to --myVariable
cssVar.myVariable = 'red';
// get the value of --myVariable
console.log( cssVar.myVariable );
Any change applied to the Object properties, is translated automatically to the CSS variables.
Available in : https://github.com/colxi/css-global-variables
add a comment |
up vote
6
down vote
up vote
6
down vote
The native solution
The standard methods to get/set CSS3 variables are .setProperty()
and .getPropertyValue()
.
If your Variables are Globals (declared in :root
), you can use the following, for getting and setting their values.
// setter
document.documentElement.style.setProperty('--myVariable', 'blue');
// getter
document.documentElement.style.getPropertyValue('--myVariable');
However the getter will only return the value of a var, if has been set, using .setProperty()
.
If has been set through CSS declaration, will return undefined
. Check it in this example:
let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
<div>Red background set by --myVariable</div>
To avoid that unexpected behavior you have to make use of the getComputedStyle()
method , before calling .getPropertyValue()
.
The getter will then , look lik this :
getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');
In my opinion, accessing CSS variables should be more simple, fast, intuitive and natural...
My personal approach
I've implemented CSSGlobalVariables
a tiny (<3kb) javascript helper wich automatically detects and packs into an Object, all the active CSS global variables in a document, for easier acces & manipulation.
// set a new value to --myVariable
cssVar.myVariable = 'red';
// get the value of --myVariable
console.log( cssVar.myVariable );
Any change applied to the Object properties, is translated automatically to the CSS variables.
Available in : https://github.com/colxi/css-global-variables
The native solution
The standard methods to get/set CSS3 variables are .setProperty()
and .getPropertyValue()
.
If your Variables are Globals (declared in :root
), you can use the following, for getting and setting their values.
// setter
document.documentElement.style.setProperty('--myVariable', 'blue');
// getter
document.documentElement.style.getPropertyValue('--myVariable');
However the getter will only return the value of a var, if has been set, using .setProperty()
.
If has been set through CSS declaration, will return undefined
. Check it in this example:
let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
<div>Red background set by --myVariable</div>
To avoid that unexpected behavior you have to make use of the getComputedStyle()
method , before calling .getPropertyValue()
.
The getter will then , look lik this :
getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');
In my opinion, accessing CSS variables should be more simple, fast, intuitive and natural...
My personal approach
I've implemented CSSGlobalVariables
a tiny (<3kb) javascript helper wich automatically detects and packs into an Object, all the active CSS global variables in a document, for easier acces & manipulation.
// set a new value to --myVariable
cssVar.myVariable = 'red';
// get the value of --myVariable
console.log( cssVar.myVariable );
Any change applied to the Object properties, is translated automatically to the CSS variables.
Available in : https://github.com/colxi/css-global-variables
let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
<div>Red background set by --myVariable</div>
let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
<div>Red background set by --myVariable</div>
edited Mar 24 at 1:03
answered Mar 20 at 5:38
colxi
2,0081726
2,0081726
add a comment |
add a comment |
up vote
1
down vote
You could add something like below (without using class variables)
function loadTheme() {
var htmlTag = document.getElementById("myDiv");
var yourSelect = document.getElementById("themeSelect");
var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
console.log("selected theme: " + selectedTheme);
// reset class names
htmlTag.className = '';
// add selected theme
htmlTag.className = 'theme' + selectedTheme;
}
.theme1 {
color: blue;
}
.theme2 {
color: red;
}
<div id="myDiv">
test
</div>
<select id="themeSelect" onChange="loadTheme()">
<option value="1">Theme 1</option>
<option value="2">Theme 2</option>
</select>
Downvoted because it doesn't answer the question at all.
– Ced
Jun 3 '17 at 17:34
@Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
– ochi
Jun 3 '17 at 20:11
1
changed my vote
– Ced
Jun 3 '17 at 20:26
add a comment |
up vote
1
down vote
You could add something like below (without using class variables)
function loadTheme() {
var htmlTag = document.getElementById("myDiv");
var yourSelect = document.getElementById("themeSelect");
var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
console.log("selected theme: " + selectedTheme);
// reset class names
htmlTag.className = '';
// add selected theme
htmlTag.className = 'theme' + selectedTheme;
}
.theme1 {
color: blue;
}
.theme2 {
color: red;
}
<div id="myDiv">
test
</div>
<select id="themeSelect" onChange="loadTheme()">
<option value="1">Theme 1</option>
<option value="2">Theme 2</option>
</select>
Downvoted because it doesn't answer the question at all.
– Ced
Jun 3 '17 at 17:34
@Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
– ochi
Jun 3 '17 at 20:11
1
changed my vote
– Ced
Jun 3 '17 at 20:26
add a comment |
up vote
1
down vote
up vote
1
down vote
You could add something like below (without using class variables)
function loadTheme() {
var htmlTag = document.getElementById("myDiv");
var yourSelect = document.getElementById("themeSelect");
var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
console.log("selected theme: " + selectedTheme);
// reset class names
htmlTag.className = '';
// add selected theme
htmlTag.className = 'theme' + selectedTheme;
}
.theme1 {
color: blue;
}
.theme2 {
color: red;
}
<div id="myDiv">
test
</div>
<select id="themeSelect" onChange="loadTheme()">
<option value="1">Theme 1</option>
<option value="2">Theme 2</option>
</select>
You could add something like below (without using class variables)
function loadTheme() {
var htmlTag = document.getElementById("myDiv");
var yourSelect = document.getElementById("themeSelect");
var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
console.log("selected theme: " + selectedTheme);
// reset class names
htmlTag.className = '';
// add selected theme
htmlTag.className = 'theme' + selectedTheme;
}
.theme1 {
color: blue;
}
.theme2 {
color: red;
}
<div id="myDiv">
test
</div>
<select id="themeSelect" onChange="loadTheme()">
<option value="1">Theme 1</option>
<option value="2">Theme 2</option>
</select>
function loadTheme() {
var htmlTag = document.getElementById("myDiv");
var yourSelect = document.getElementById("themeSelect");
var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
console.log("selected theme: " + selectedTheme);
// reset class names
htmlTag.className = '';
// add selected theme
htmlTag.className = 'theme' + selectedTheme;
}
.theme1 {
color: blue;
}
.theme2 {
color: red;
}
<div id="myDiv">
test
</div>
<select id="themeSelect" onChange="loadTheme()">
<option value="1">Theme 1</option>
<option value="2">Theme 2</option>
</select>
function loadTheme() {
var htmlTag = document.getElementById("myDiv");
var yourSelect = document.getElementById("themeSelect");
var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
console.log("selected theme: " + selectedTheme);
// reset class names
htmlTag.className = '';
// add selected theme
htmlTag.className = 'theme' + selectedTheme;
}
.theme1 {
color: blue;
}
.theme2 {
color: red;
}
<div id="myDiv">
test
</div>
<select id="themeSelect" onChange="loadTheme()">
<option value="1">Theme 1</option>
<option value="2">Theme 2</option>
</select>
edited Jun 3 '17 at 20:26
Ced
6,68313881
6,68313881
answered Dec 28 '16 at 23:22
ochi
8,59843247
8,59843247
Downvoted because it doesn't answer the question at all.
– Ced
Jun 3 '17 at 17:34
@Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
– ochi
Jun 3 '17 at 20:11
1
changed my vote
– Ced
Jun 3 '17 at 20:26
add a comment |
Downvoted because it doesn't answer the question at all.
– Ced
Jun 3 '17 at 17:34
@Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
– ochi
Jun 3 '17 at 20:11
1
changed my vote
– Ced
Jun 3 '17 at 20:26
Downvoted because it doesn't answer the question at all.
– Ced
Jun 3 '17 at 17:34
Downvoted because it doesn't answer the question at all.
– Ced
Jun 3 '17 at 17:34
@Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
– ochi
Jun 3 '17 at 20:11
@Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
– ochi
Jun 3 '17 at 20:11
1
1
changed my vote
– Ced
Jun 3 '17 at 20:26
changed my vote
– Ced
Jun 3 '17 at 20:26
add a comment |
up vote
0
down vote
It would probably be easier to define classes in your CSS that contain the various theme styles (.theme1 {...}
, .theme2 {...}
, etc) and then change the class with JS based on the selected value.
2
This is more of a comment than an answer
– ochi
Dec 28 '16 at 23:01
I didn't think about that. I'll give that a shot and get back to you
– David Richards
Dec 28 '16 at 23:10
add a comment |
up vote
0
down vote
It would probably be easier to define classes in your CSS that contain the various theme styles (.theme1 {...}
, .theme2 {...}
, etc) and then change the class with JS based on the selected value.
2
This is more of a comment than an answer
– ochi
Dec 28 '16 at 23:01
I didn't think about that. I'll give that a shot and get back to you
– David Richards
Dec 28 '16 at 23:10
add a comment |
up vote
0
down vote
up vote
0
down vote
It would probably be easier to define classes in your CSS that contain the various theme styles (.theme1 {...}
, .theme2 {...}
, etc) and then change the class with JS based on the selected value.
It would probably be easier to define classes in your CSS that contain the various theme styles (.theme1 {...}
, .theme2 {...}
, etc) and then change the class with JS based on the selected value.
answered Dec 28 '16 at 22:59
johnniebenson
47039
47039
2
This is more of a comment than an answer
– ochi
Dec 28 '16 at 23:01
I didn't think about that. I'll give that a shot and get back to you
– David Richards
Dec 28 '16 at 23:10
add a comment |
2
This is more of a comment than an answer
– ochi
Dec 28 '16 at 23:01
I didn't think about that. I'll give that a shot and get back to you
– David Richards
Dec 28 '16 at 23:10
2
2
This is more of a comment than an answer
– ochi
Dec 28 '16 at 23:01
This is more of a comment than an answer
– ochi
Dec 28 '16 at 23:01
I didn't think about that. I'll give that a shot and get back to you
– David Richards
Dec 28 '16 at 23:10
I didn't think about that. I'll give that a shot and get back to you
– David Richards
Dec 28 '16 at 23:10
add a comment |
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41370741%2fhow-do-i-edit-a-css-variable-using-js%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I don't recall
--main-text-color
being a valid CSS attribute. Is that using a a pre-processor?– ochi
Dec 28 '16 at 22:43
No it is a css variable. I found out about them in this article
– David Richards
Dec 28 '16 at 22:44
broken-links.com/2014/08/28/…
– David Richards
Dec 28 '16 at 22:44
2
Yes, those CSS variables use a 'native' pre-processor (basically, they eventually get converted into the real property/attribute beforehand). BTW, this feature is not widely supported by all browsers (only FF, from the article. I dunno about other browsers) - in any case, your syntax is incorrect if you want to manipulate them in JS. You need to manipulate properties (not attributes, it seems) - so try
htmlTag[0].styles.setProperty('--main-text-color', '#FFCF40');
– ochi
Dec 28 '16 at 22:54
I copied your answer in and now the error is that it can not set property of undefined. Could I bother you for a fiddle example?
– David Richards
Dec 28 '16 at 23:12