Reputation: 1549
I have a css variable being defined by a randomizer function, I need this variable to generate a random background color from the list, every time I enter the page:
@all-background-colors: "#7B8AA8,#00ADD5,#E93C43,#FC8383";
@background-color: color(~`@{all-background-colors}.split(',')[Math.floor(Math.random()*@{all-background-colors}.split(',').length)]`);
However it seems that the function gets executed every time I use this variable in my css - resulting in many different colors being used across the web page.
is there any way to escape this and transform the variable to a string one after it's defined by the function?
Upvotes: 1
Views: 1032
Reputation: 72261
Wrapping the generating code in a mixin, and then calling that mixin once seems to have resolved the issue. So this:
@all-background-colors: "#7B8AA8,#00ADD5,#E93C43,#FC8383";
.generateColor() { /* define mixin */
@background-color: color(~`@{all-background-colors}.split(',')[Math.floor(Math.random()*@{all-background-colors}.split(',').length)]`);
}
.generateColor(); /* call the mixin which sets the variable once */
.test1 {
color-fixed: @background-color;
}
.test2 {
color-fixed: @background-color;
}
.test3 {
color-fixed: @background-color;
}
Which for me produced this consistent test css:
.test1 {
color-fixed: #7b8aa8;
}
.test2 {
color-fixed: #7b8aa8;
}
.test3 {
color-fixed: #7b8aa8;
}
Upvotes: 5