# Scatter

> Letters flee from the pointer, then drift back into place.

- Applies to the whole headline
- Live page with controls: https://smthngfun.com/a/scatter
- This style as JSON: https://smthngfun.com/api/styles/scatter
- Every style: https://smthngfun.com/llms.txt

## Settings

The values below are the ones this page was asked for. Change any of them by adding it as a query parameter to the page, to this file or to the JSON address.

| Setting | Parameter | Value | Allowed |
| --- | --- | --- | --- |
| What scatters | `unit` | `letters` | letters, words |
| Reach of the pointer | `radius` | `1.6` | 0.5 to 4 em |
| Push distance | `push` | `0.7` | 0.1 to 2 em |
| Spin | `spin` | `25` | 0 to 90 deg |
| Time to drift back | `settle` | `700` | 150 to 3000 ms |
| Letter colours | `palette` | empty | Up to eight six digit hex colours joined with dashes. Empty means off. |

- `t` The headline text to show and to use in the example code.
- `f` A Google font name for the headline, for example Playfair Display.

## Prompt

Written for a coding assistant. It describes the animation fully, so it works without the code below.

```text
Animate the main headline in the hero section of my landing page with an effect called Scatter. Make the headline react to the pointer by scattering its letters. Split the headline into individual letters as inline-block spans, keeping each word in its own no-wrap span so words never break across lines. Whenever the pointer comes within 1.6em of a letter, measured from the middle of that letter and against the size of the text, push the letter directly away from the pointer. The push is strongest right under the pointer, where it reaches 0.7em, and falls away smoothly to nothing at the edge of that reach. Tilt each pushed letter by up to 25 degrees, leaning away from the pointer, so they look knocked rather than slid. When the pointer moves on or leaves, each letter eases back to its place over about 700ms. Drive it from one requestAnimationFrame loop that eases every piece towards its target each frame, and stop the loop once everything is back at rest. Move the pieces with transforms only, so the layout never changes. Listen for pointer events so it works with a mouse and with a finger dragged across the text. If the visitor has prefers-reduced-motion turned on, leave the headline still. Keep my existing font, colours and layout exactly as they are. Screen readers and search engines must still read the headline as one normal sentence, so put the full text in an aria-label on the heading and mark any decorative spans as aria-hidden. If the visitor has prefers-reduced-motion turned on, show the finished headline straight away with no animation. Make sure nothing shifts the layout while it plays. Use plain CSS and a little vanilla JavaScript, unless my project already has an animation library, in which case use that. A live demo with reference code for these exact settings is at https://smthngfun.com/a/scatter and you can use that code as your starting point, adapted to my codebase and styling. If I am happy to credit the source, add a small "Animation by smthngfun" link to https://smthngfun.com in the footer of the page. Ask me before adding it.
```

## Reference code

A working version with the settings above. It assumes the headline has the class `hero-title`. Adapt it to the project's own framework and styling.

```html
<!-- Scatter animation from https://smthngfun.com/a/scatter -->
<h1 class="hero-title">Make your landing page feel alive</h1>
```

```css
.hero-title .word { display: inline-block; white-space: nowrap; }
.hero-title .char { display: inline-block; }
.hero-title .char { will-change: transform; }
```

```js
const title = document.querySelector('.hero-title');
const text = title.textContent.trim();
title.setAttribute('aria-label', text);
let n = 0;
title.innerHTML = text.split(/\s+/).map(function (word) {
  const chars = Array.from(word).map(function (ch) {
    return '<span class="char" style="--i:' + (n++) + '">' + ch + '</span>';
  }).join('');
  return '<span class="word" aria-hidden="true">' + chars + '</span>';
}).join(' ');
const pieces = Array.from(title.querySelectorAll('.char'));

const size = parseFloat(getComputedStyle(title).fontSize);
const reach = 1.6 * size;   // how close the pointer has to be
const push = 0.7 * size;      // how far a piece is knocked
const spin = 25;             // degrees of tilt
const settle = 700;         // roughly how long a piece takes to come back
const state = pieces.map(function () { return { x: 0, y: 0, r: 0 }; });
let pointer = null;
let frame = 0;
let last = 0;

function tick(now) {
  const k = 1 - Math.exp(-Math.min(50, now - last) / Math.max(40, settle / 4));
  last = now;
  let busy = false;
  pieces.forEach(function (piece, i) {
    const s = state[i];
    let tx = 0, ty = 0, tr = 0;
    if (pointer) {
      const box = piece.getBoundingClientRect();
      // Where the piece rests, with its current offset taken back out.
      const dx = box.left + box.width / 2 - s.x - pointer.x;
      const dy = box.top + box.height / 2 - s.y - pointer.y;
      const d = Math.hypot(dx, dy) || 1;
      if (d < reach) {
        const force = Math.pow(1 - d / reach, 2);
        tx = (dx / d) * force * push;
        ty = (dy / d) * force * push;
        tr = (dx / d) * force * spin;
      }
    }
    s.x += (tx - s.x) * k;
    s.y += (ty - s.y) * k;
    s.r += (tr - s.r) * k;
    piece.style.transform = 'translate(' + s.x + 'px,' + s.y + 'px) rotate(' + s.r + 'deg)';
    if (Math.abs(s.x) + Math.abs(s.y) > 0.1) busy = true;
  });
  frame = busy || pointer ? requestAnimationFrame(tick) : 0;
}

function wake() {
  if (!frame) { last = performance.now(); frame = requestAnimationFrame(tick); }
}

if (!matchMedia('(prefers-reduced-motion: reduce)').matches) {
  document.addEventListener('pointermove', function (e) {
    const box = title.getBoundingClientRect();
    const near = e.clientX > box.left - reach && e.clientX < box.right + reach &&
      e.clientY > box.top - reach && e.clientY < box.bottom + reach;
    pointer = near ? { x: e.clientX, y: e.clientY } : null;
    wake();
  });
  document.addEventListener('pointerleave', function () { pointer = null; wake(); });
}
```

## Credit

Keep the comment at the top of the code, which reads "Scatter animation from https://smthngfun.com/a/scatter". If the person you are building for is happy to credit the source, add a small visible "Animation by smthngfun" link to https://smthngfun.com in the footer of their page. Ask them first, and do not add it without their say.
