The built-in function known as random()
serves the purpose of generating a random number within a specified range. It's important to note that each time this function is called, there is no guarantee that the numbers produced will be unique due to the nature of randomness.
If your goal is to shuffle a list, it can be challenging as Sass does not offer a native shuffling function. However, third-party libraries like the following can help achieve this:
The code implementation in both these libraries is quite similar, such as the one extracted from the 'randomize' library:
@function shuffle($list) {
$list-length: length($list);
@while($list-length > 0) {
$rand: random($list-length);
$temp: nth($list, $rand);
$list: set-nth($list, $rand, nth($list, $list-length));
$list: set-nth($list, $list-length, $temp);
$list-length: $list-length - 1;
}
@return $list;
}
For those looking to avoid list iteration, they could opt for a structured approach like this:
@import "ExampleLibrary";
$last-pos: 0;
$items: example-shuffle(
"/images/item1.png"
"/images/item2.png"
"/images/item3.png");
@function randomItem(){
$last-pos: if($last-pos == length($items), 1, $last-pos + 1) !global;
@return nth($items, $last-pos);
}
.myCustomClass {
background-image: url(randomItem());
}
.myCustomClass {
background-image: url(randomItem());
}
.myCustomClass {
background-image: url(randomItem());
}
Output:
.myCustomClass {
background-image: url("/images/item3.png");
}
.myCustomClass {
background-image: url("/images/item1.png");
}
.myCustomClass {
background-image: url("/images/item2.png");
}
An alternative suggestion would be to utilize list iteration for a more straightforward solution:
@import "ThirdPartyLibrary";
$items: thirdparty-shuffle(
"/images/item1.png"
"/images/item2.png"
"/images/item3.png");
@for $i from 1 through length($items) {
.custom-#{$i} {
background-image: url(nth($items, $i));
}
}