I want to create a simple script that changes LESS variables and print the CSS output in a div.
this is my HTML
<input type="text" id="choose-color" onchange="ModifyColorsInLess()">
<button onclick="writeCSS()">aggiorna</button>
<div id="lesscode"></div>
This is my js
function writeCSS(){
var lessCode = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status === 200 && xmlhttp.readyState === 4){
lessCode = xmlhttp.responseText;
new(less.Parser)().parse(lessCode, function (e, tree) {
document.getElementById('lesscode').innerHTML = tree.toCSS().replace(/\n/g,"<br>");
});
}
};
xmlhttp.open("GET","css/styles.less",true);
xmlhttp.send();
}
function ModifyColorsInLess() {
less.modifyVars(
{
'@colore-body': $("#choose-color").val()
}
);
}
The script prints CSS code correctly, but if i insert a new color value in the input type="text" and call the writeCSS function, it doesn't print my variable edit. I think the problem is that "modifyvar" does not change the file "styles.less", so when I call the function writeCSS() does not detect changes made. is there a way to print the css dynamically detecting changes made with modifyvar?
update When you allow the compiled styles are directly applied on your page, you can simply call `modifyVars as follows:
Demo: http://plnkr.co/14MIt4gGCrMyXjgwCsoc
end update
Based on How to show the compiled css from a .less file in the browser?, How to update variables in .less file dynamically using AngularJS and Less: Passing option when using programmatically (via API) (you should also read: http://lesscss.org/usage/#programmatic-usage) you should be able to use the code like that shown below:
demo: http://plnkr.co/YbdtOwOeQPC1k9Vq4ZBv
And finally based on Force Cache-Control: no-cache in Chrome via XMLHttpRequest on F5 reload you can prevent caching of your source file with the following code:In the above the
env: "development"
setting prevents your source files from caching. To clear the cache otherwise, you should callless.refresh(true)
before your less.render call.Make sure that
another.less
in the above is in the same folder as yourstyles.less
file. Notice that import (when using less in browser) are read with a XMLHttpRequest too. So your imported files should be readable by browser and their paths should be relative to thestyles.less
file. Also see http://lesscss.org/usage/#using-less-in-the-browser-relativeurls