Re: [csswg-drafts] [css-values] random() function (#2826)

I've been looking for something like `Math.random()` in CSS for a few years, and experimenting with different use cases and ways they can be achieved. If I were to set this up today I'd use CSS variables as the handoff between JavaScript and CSS, which also gives you full control over how and when these values are calculated. Here's a demo:

```html
<div>I use random from CSS</div>
<div style="--random-bg: 360;">I use random from DOM</div>
<div class=load>I am randomized once per load event</div>
<div class=click>I am randomized once per click event</div>

<style>
  div {
    --random-bg: 360;
    background-color: hsl(calc(var(--random-bg) * 1deg), 75%, 50%);
  }
  .load {
    --randomized-on-load: 360;
    background-color: hsl(calc(var(--randomized-on-load) * 1deg), 75%, 50%);
  }
  .click {
    --randomized-on-click: 360;
    background-color: hsl(calc(var(--randomized-on-click) * 1deg), 75%, 50%);
  }
</style>

<script type=module>
  import computedVariables from 'https://unpkg.com/computed-variables/index.es.js'

  computedVariables(
    '--random-',
    value => Math.random() * value,
    window,
    ['load']
  )

  computedVariables(
    '--randomized-on-load',
    value => Math.random() * value,
    window,
    ['load']
  )

  computedVariables(
    '--randomized-on-click',
    value => Math.random() * value,
    window,
    ['click']
  )
</script>
```

You can create a CSS variable like `--example: 10;` and use the Javascript function `value => Math.random() * value` to generate a random number between `0` and the supplied value. In this demo I've created a few different background colors and picked random numbers between 0 and 360. The next part is where the control comes in:

- you can have things calculated once per load
- you can have things calculated once per event (like every click event)
- the values cascade nicely in CSS and DOM exactly how you'd expect

It seems like everything people want is possible already! In the past I'd have said that this was a much-needed feature that should be added to CSS for animation and other things, but considering how flexible and powerful it is to use JavaScript's own `Math.random()` with styles by way of CSS variables I think a lot of that pressure is removed.

It's also easy to create random choice function in JavaScript that can pick randomly from a list of values given in CSS too, like `--choose: ['lime', 'hotpink']` and assign the chosen value to the CSS variable for CSS to make use of in styles.

-- 
GitHub Notification of comment by tomhodgins
Please view or discuss this issue at https://github.com/w3c/csswg-drafts/issues/2826#issuecomment-468402592 using your GitHub account

Received on Thursday, 28 February 2019 19:21:57 UTC