I have looked around and I've seen one solution where in your html, you'd have a tag dedicated to pass sass variables to javascript. I'm talking about the second answer from
Is there a way to import variables from javascript to sass or vice versa?
I also tried using html
<div class="selector"></div>
with css
.selector { content: "stuff"; }
but looking at the dom in the developer tools, it doesn't get added even though we can see it on the rendered page, so I cannot pick it up with javascript
$('.selector').text()
How does everyone do it?
I believe that injecting SASS variables via CSS
content
property is a very hackish way to do things.Instead, you can store the variables in a separate location and have them read both by SASS and JS.
First, store a list of breakpoints in a
breakpoints.json
file:Then use Ruby to read this JSON file and make its contents available as a SASS list via a SASS function. Put this into your Compass
config.rb
:In your SASS code, read breakpoints like this:
In JS, use jQuery's
.get
method to request the JSON file like this:When i was assembling this setup, I found an existing solution here, but i decided to reimplement it using my favorite SASS tools: Singularity and Breakpoint Slicer.
For your convenience, i've built a proof-of-concept GitHub project with everything set up nicely, featuring some ugly JS code. :)
And here's a live demo!
Sharing state trough CSS
content
property seems dirty. I don't like the idea of making extra XHR requests either.I've thought of building a custom solution that would just compile SASS file and JS module. But it turned out there's an
npm
package called rosetta. It does exactly that. Formats of output are pretty flexible and it didn't take me long to set it up as aGrunt.js
task.$ npm install rosetta
Here's example Gruntfile.js:
And package.json:
After all that you just need to import _shared_variables.scss in SASS and use rosetta.js module in your JavaScript to access common variables. As you make changes to the *.rose files your styles and JS will be updated.
If you are using
GULP
orGRUNT
(I hope you are using the first one)This example shows how to do it using
gulp
:Define the colors in the gulpfile, or in another file and then import it to your gulpfile, and then you can dynamically build both the
SCSS
variables and the javascript like so:variables_template.scss (not to be imported in your main scss file)
app.js (some js file which holds the colors variable)
gulpfile.js
Similar NPM gulp packages for SCSS variables:
Not sure about "industry standard", but it's a very handy technique and not too difficult. The content of pseudo elements is not available via
text()
though, you have to usegetComputedStyle
.Example using
body:after
:Sass (using the compass breakpoint extension):
JavaScript:
Credit: I first saw this technique here: https://coderwall.com/p/_ldtkg