Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
const cssVars = (target = document.documentElement, key, value) => (
key == null
? [...target.style].reduce((hash, key) => hash.slice(0,2) != '--' ? hash : Object.assign(hash, {
[key.slice(2)] : target.style.getPropertyValue(key)
}), {})
: typeof key == 'object'
? Object.entries(key).forEach(entry => {
cssVars(target, ...entry)
})
: value == undefined
? target.style.getPropertyValue('--' + key)
: target.style.setProperty('--' + key, value)
)
try { module.exports = cssVars } catch(e) {}
Owner

barneycarroll commented Sep 25, 2017

cssVars

Provides a simple JS interface to CSS variables. In this abstraction, the -- prefix for CSS variable keys disappears.


cssVars(el)

Returns a hash of CSS property key values for el (el defaults to CSS :root, ie document.documentElement).

cssVars(el, 'thing')

Returns --thing property as currently computed for el.

cssVars(el, 'thing', 'red')

Sets --thing to red

cssVars(el, {thing1: 'red', thing2:'blue'})

Sets --thing1 to red & --thing2 to blue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment