If your LESS style sheet is being processed in the browser (and not sent as server CSS) you can change the variables in running time. The file will not be loaded again, but it will be recompiled.
Your Less style sheet should be loaded in the browser, so you should have something like:
<link rel="stylesheet/less" type="text/css" href="estilo.less" />
After loading the style sheet, you should load the less.js
:
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/1.6.3/less.min.js"></script>
(you can also download from https://github.com/less)
With this you can use the global object less
which allows you to obtain various information from the style sheet, and change variables. This object and its components are not very well documented, but you can discover a lot via introspection in the Javascript console.
One of the documented features is changing variables, which you can perform through the function modifyVars()
that receives a map of variables that must be changed:
less.modifyVars({
'@fundo': '#eee',
'@texto': 'rgb(255, 135, 176)'
});
See more about this here
There is a lot more that can be done with Less in the browser, but a lot is not documented, so it may change in the future. You can extract data from a Less style sheet that is in your domain (regardless of whether it is being used on your page) with the less.Parser
, that you can create so:
var parser = new(less.Parser);
And then process using parse()
:
parser.parse("@v1: 5pt; @v2: 10pt; h1 {font-size: @v1}", function (e, tree) { ... });
For example, the following script extracts all variables from folha-de-estilo.less
and lists within a block <ul id="varlist"></id>
you have on the page.
$( document ).ready(function() {
var parser = new(less.Parser);
$.get( "/styles/less/folha-de-estilo.less", function( data ) {
parser.parse(data, function (e, tree) {
var variables = tree.variables();
console.log(variables)
for (i in variables) {
var name = variables[i].name;
var value = variables[i].value.toCSS(); // FALHA se variavel contiver expressao
$("#varlist").append("<li>"+name + ":" + value+"</li>");
}
});
});
});
Only works for Less variables that have CSS values inside (cannot have expressions). This can be useful to take advantage of values used in scripts.
Our very good guy, that’s what I needed.
– Weslley Oliveira
I had no idea it was possible, +1
– Paulo Roberto Rosa