Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SASS random() always returns same value, why?

As you can see here: http://codepen.io/MyXoToD/pen/alkmL I'm trying to convert some javascript functions into SASS. Everything works fine but this one function...

I want to convert this:

var pallete = Math.floor(Math.random() * 210);

$("article h2").each(function(i) {
  var hue = pallete + (i * 15);
  var css = 'background:hsl(' + hue + ',85%,70%); color:hsl(' + hue + ',45%,55%);';
  $(this).attr("style", css);
});

Into something like this:

@for $i from 1 through $articles {
  &:nth-child(#{$i}) {
    $random: random(210);
    $hue: $random + ($i * 15);
    background-color: hsl($hue, 85%, 70%);
    color: hsl($hue, 45%, 55%);
  }
}

My problem in this case is, that random(210) always returns the same value on each page load. Is it possible to get different values from random on each run through @for?

like image 840
MyXoToD Avatar asked Nov 14 '25 16:11

MyXoToD


1 Answers

No, that's not possible in any proper production setup. Browsers only understand CSS so SASS and pretty much all other CSS preprocessors usually run once (on the server), not on the client for each page load.

While for example LESS has a client-side compiler (less.js), using it slows down the page loading process and is usually only suitable for development. If you really want dynamic colors, consider building the relevant CSS using JavaScript or keeping the old code.

like image 138
ThiefMaster Avatar answered Nov 17 '25 06:11

ThiefMaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!