Get and Set global CSS properties (vars) with Vanilla JS.
It is useful to set/change CSS themes for web apps dynamically.
You can install it with NPM, Yarn or via Unpkg CDN:
npm i -S @jsweb/css-theme-vars
yarn add @jsweb/css-theme-vars
<scriptsrc="https://unpkg.com/@jsweb/css-theme-vars"></script>importcssfrom'@jsweb/css-theme-vars'constcss=require('@jsweb/css-theme-vars')If you install it via CDN, the object cssThemeVars will be global available at window scope.
There are 4 useful methods:
It sets a bundle of :root CSS variables to config a CSS theme for your project.
The obj argument can be any JSON or literal JS object.
importcssfrom'@jsweb/css-theme-vars'consttheme={'--color-accent': 'gold','--color-danger': 'crimsom','--color-primary': 'teal','--color-secondary': 'cyan','--color-warning': 'orange'}css.setTheme(theme)Now you can do this:
.text-primary {
color:var(--primary);
}
.text-danger {
color:var(--danger);
}
.text-warning {
color:var(--warning);
}It is just a convenient method that parses CSS variables from all computed styles.
So, not used vars will not be parsed.
importcssfrom'@jsweb/css-theme-vars'consttheme=css.getTheme()/*theme = { '--color-accent': 'gold', '--color-danger': 'crimsom', '--color-primary': 'teal', '--color-secondary': 'cyan', '--color-warning': 'orange'}*/constcolorPrimary=theme['--color-primary']Now you can use CSS variables in JS.
It sets a :root CSS variable programaticaly.
importcssfrom'@jsweb/css-theme-vars'css.setVar('--color-primary','blue')Now you can change your CSS variables on the fly.
If you know a :root CSS variable key, then you can get it in JS.
importcssfrom'@jsweb/css-theme-vars'constcolorPrimary=css.getVar('--color-primary')Now you can use the CSS variable in JS.
@jsweb/css-theme-vars just plays with native methods using Vanilla JS, CSS computed sytles and DOM.
So, just use your imagination! ;)