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 variable — 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 , 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 to accomplish CSS variable manipulation with JavaScript so I’m happy it’s as easy as described above!


  • Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don’t work in Firefox or Explorer (correctly so, by spec) though…

  • CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome…

  • Add Styles to Console Statements

    I was recently checking out Google Plus because they implement some awesome effects.  I opened the console and same the following message: WARNING! Using this console may allow attackers to impersonate you and steal your information using an attack called Self-XSS. Do not enter or paste code that you…

  • Modal-Style Text Selection with Fokus

    Every once in a while I find a tiny JavaScript library that does something very specific, very well.  My latest find, Fokus, is a utility that listens for text selection within the page, and when such an event occurs, shows a beautiful modal dialog in…



Source link
thanks you RSS link
( https://davidwalsh.name/css-variables-javascript)

LEAVE A REPLY

Please enter your comment!
Please enter your name here