cssVar - A jQuery plugin for handling CSS variables in Javascript
CSS variables are new to CSS3 and have many advantages over their prepocessors counterparts, such as being accessible in Javascript.
However accessing those variables in pure javascript tend to be an open door to very repetitive boilerplate, which is why I decided to created this plugin for jQuery.
It is originally a plugin from my other library (lightquery, currently in-dev), I just ported it to comply with jQuery's plugin syntax.
How to install/use ?
Witout NPM
<head>
<script src="path/to/jquery"></script>
<script src="path/to/the/cssVar/plugin"></script>
</head>
Once that is done, you can use cssVar in any script loaded after the plugin.
With NPM
npm install jq-cssvar
require("path/to/the/cssVar/plugin")($);
Accessing variables
:root{
--variable-name: 42;
}
To access this variable, we simply use
jQuery.cssVar("--variable-name");
jQuery.cssVar("variable-name");
Variable name selector
Because all CSS variable must start with "--", I made it possible to use the variables' names without "--".
Therefore,
jQuery.cssVar("--x");
and
jQuery.cssVar("x");
are strictly equivalent.
Modifying global variables
:root{
--var: 404
}
Just like any other plugin of jQuery, cssVar adopts the getter/setter syntax, therefore we can modify this variable like so :
jQuery.cssVar("var");
jQuery.cssVar("var", 42);
jQuery.cssVar("var");
Non-global (instance) variables
Even though using only global CSS variables is the best use case, sometimes you just need to have non-global variables/modify those variables locally.
Therefore cssVar is also ready for this.
:root{
--var1: 404;
}
.class{
--var1: 42;
--var2: 40;
}
jQuery(".class").cssVar("var1");
jQuery(".class").cssVar("var2");
jQuery.cssVar("var1");
jQuery(".class").eq(2).cssVar("var1", 41);
jQuery(".class").eq(0).cssVar("var1");
jQuery(".class").eq(2).cssVar("var1");
jQuery(".class").cssVar("var1", 440);
jQuery(".class").eq(0).cssVar("var1");
jQuery(".class").eq(2).cssVar("var1");
Specifications
- The getter only retrieves the variable's value from the first element of the matched set
- The setter sets the variable's value for each element of the matched set
- CSS variables only accept numbers and strings, those are the only types of values that you can set those variables to
- If an error occurs, it returns what the method was called on (the matched set if instance, jquery if global)
- All modifications you can do to those variables follow the same rules as if they were done in CSS (cf. How to use CSS variables (MDN))