Save Expand icon

Ron Valstar
front-end developer

LESS variables to JavaScript

LESS CSS is great and all but what if you want to use the same LESS variables in JavaScript.

Here’s an easy solution I used for a site I recently made.
In LESS create class rules within a non-existing id. Then read them by traversing the document.styleSheets.

Here’s a Github gist and here’s a fiddle.

So in my LESS file I have the following:

@thumbsWidth: 654px;
@thumbsTop: 123px;
#less {
    .thumbsWidth { width: @thumbsWidth; }
    .thumbsTop { width: @thumbsTop; }
}

Then call the function: getLessVars('less');

Which returns the following object with the LESS variables:

{
    thumbsWidth: 123,
    thumbsTop: 456
}

easy