How to Get and Set CSS Variable Values with JavaScript


CSS variables are a very welcome addition to the language, despite them being incredibly basic.  Sure we could use SASS or stylus but languages should never count on developers relying on frameworks and toolkits to accomplish what we know we need.  And just like every other part of a webpage, you can get and manipulate CSS variable values — let’s check out how!


Setting and Using a CSS Variables


The traditional method of using native CSS variables is adding it to root:



:root {
    --my-variable-name: #999999;
}


Simple.  Also remember that CSS variables are nowhere near as powerful as variables within SASS, stylus, etc.


Getting a CSS Variable’s Value


To retrieve the value of a CSS variable within the window, you use getComputedStyle and getPropertyValue:



getComputedStyle(document.documentElement)
    .getPropertyValue('--my-variable-name'); // #999999


The computed variable value comes back as a string.


Setting a CSS Variable’s Value


To set the value of a CSS variable using JavaScript, you use setProperty on documentElement‘s style property:



document.documentElement.style
    .setProperty('--my-variable-name', 'pink');


You’ll immediately see the new value applied everywhere the variable is used.


I had anticipated the need for disgusting hacks to accomplish CSS variable manipulation with JavaScript so I’m happy it’s as easy as described above!

  • How to Create a Twitter Card
  • Page Visibility API

    One event that’s always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

  • MooTools PulseFade Plugin

    I was recently driven to create a MooTools plugin that would take an element and fade it to a min from a max for a given number of times. Here’s the result of my Moo-foolery. The MooTools JavaScript Options of the class include: min: (defaults to .5) the…

  • Dynamically Load Stylesheets Using MooTools 1.2

    Theming has become a big part of the Web 2.0 revolution. Luckily, so too has a higher regard for semantics and CSS standards. If you build your pages using good XHTML code, changing a CSS file can make your website look completely different.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img