Sometimes you want to include some CSS in a JavaScript file. Maybe it's a standalone widget. A big ol' string is a pain to manage, and won't minify so pretty. Especially if you want your CSS safely namespaced. For example:
.widget {
background: #abc123;
width: 100px;
/* ... */
}
.widget .doodad {
background: #abc123;
/* ... */
}
.widget .doodad:hover {
background: red;
}
/* and so on */
Wouldn't it be neat if you could bundle up that CSS in a slightly more JS-friendly and compact way? And maybe get a hand with all that prefixing business?
But it does come up sometimes, right? JSS to the rescue!
The JSS for the aforementioned widget would look like the following:
var style = {
"&": "background: #abc123; width: 100px",
".doodad": {
"&": "background: #abc123",
"&:hover": "background: red"
}
};
Next, we pass that object to the jss
function with the parameter namespace
:
var css = jss(style, '.widget');
Poof! css
is the re-constituted style above! That's kind-of nifty. Drop that in a <style>
and you're off to the races!
But wait! There's more! Let's say we had some repeated values in the above (like our background color). If we write the JSS to look like this:
var style = {
"&": "background: {bg}; width: 100px",
".doodad": {
"&": "background: {bg}",
"&:hover": "background: red"
}
};
...we can now pass a third optional vars
object to the jss
function to do basic value replacement! It looks like this:
var css = jss(style, '.widget', { "bg": "#abc123" });
We can actually replace any arbitrary string in the style rules this way:
var style = {
"&": "{bg}; width: 100px",
".doodad": {
"&": "{bg}",
"&:hover": "background: red"
}
};
var css = jss(style, '.widget', { "bg": "background: #abc123" });
Did I mention the jss
inflater is 355 bytes minified?
Aw, shucks. I do what I can.
No copyright intended.
What's up with the spaces at the beginning of some of the selectors? Why not use '&' for the reference to the current selector, like in LESS and company?
Also, this is horrible. Good job.