1

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?

1 Answer 1

5

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

this works great, thanks! I had to define the less environment to "development", otherwised the color was cached and the same color was shown on refresh, but I guess that's acceptable..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.