Reputation: 91
I have created a global variable in LESS css and assigned it a value. I used that value in multiple classes in CSS. I want to override that global variable dynamically through javascript.
@color: #f938ab;
body {
font-family: 'Raleway', sans-serif;
color: @color;
}
Can I override above variable using JavaScript code or something like below?
var color = //color from database;
document.documentElement.style.setProperty('@color', color);
Or is there any other method in CSS?
Upvotes: 5
Views: 2408
Reputation: 613
According to the documentation:
Enables run-time modification of Less variables. When called with new values, the Less file is recompiled without reloading. Simple basic usage:
less.modifyVars({
'@buttonFace': '#5B83AD',
'@buttonText': '#D9EEF2'
});
This assumes that you use less on the client side, otherwise you will need to create one css class per color and switch it with javascript. But the last solution is only possible if you have a specific list of possible color because hexadecimal handle 16 777 216 different one.
Upvotes: 0
Reputation: 6619
The best way to do this is to add dynamic class on the body and change the value of @color based on the class added on the body and then compile the LESS into css.
@color: #f938ab;
body.class1{
@color: color1;
}
body {
font-family: 'Raleway', sans-serif;
color: @color;
}
and add the class on body using javascript.
Upvotes: 0
Reputation: 6722
You need to rethink your approach.
Maybe you could apply a class to the main container (body
?) and change your css to apply specific colours depending on that class? You could possibly update the value of this colour dynamically.
Also, depending on where you compile your LESS file you might have some more options. If you compile it serverside on every request (bad approach) and you read the DB on serverside too than you could change the value of this variable just by altering the file.
If you generate the CSS on client side (bad approach) you could possibly do a similar thing.
Both solutions are quite bad and 'hacky' and would heavily impact the perfomance
Upvotes: 2