# Fade In With Blur

Fade In With Blur is a text entrance where words emerge from a blur one after another.

- Live demo: https://dmivanov.ru/experiments/fade-in-blur
- Original CodePen: https://codepen.io/divulture/pen/LEYPNay

## How to embed

Instructions for an AI agent or developer adding this effect to a website.

1. Save the two code blocks below as `shared.js` and `fade-in-blur.js` in the same folder of the project's scripts. They are plain ES modules with no build step and no dependencies.
2. Add a container with an explicit size where the effect should appear. The effect fills it completely:

   ```html
   <div id="fade-in-blur" style="position: relative; width: 100%; height: 480px;"></div>
   ```

3. Mount the effect from a module script:

   ```html
   <script type="module">
     import { mount, meta } from "./fade-in-blur.js";

     const effect = mount(document.getElementById("fade-in-blur"), { ...meta.defaults });
     // effect.update({ ... }) changes parameters at runtime.
     // effect.replay() restarts one-shot animations.
     // effect.destroy() removes the effect and its listeners.
   </script>
   ```

This animation plays once when it is mounted. Call `effect.replay()` to play it again, for example from a button or when the section scrolls into view.

The module injects its own CSS and loads its Google Font. Pixel values are authored for a 1000px-wide container and scale with the container width. In React, Vue or Svelte, call `mount` when the component mounts and `destroy` when it unmounts. Pass `{ mode: "still" }` as the third argument of `mount` to render a single static frame, for example for a preview card.

## Parameters

| Key | Control | Default | Values |
| --- | --- | --- | --- |
| `text` | Text | `"Fade in with blur"` | text, up to 60 chars |
| `size` | Size | `224` | 80–320 px |
| `blur` | Blur | `10` | 0–40 px |
| `duration` | Duration | `1500` | 300–4000 ms |
| `stagger` | Stagger | `100` | 0–500 ms |
| `textColor` | Text color | `"#FF4552"` | hex color |
| `background` | Background | `"#EFE8D8"` | hex color |

## shared.js

```js
// Shared helpers for experiment modules.
//
// Every experiment exports `meta` (title, controls, defaults) and
// `mount(stage, settings, { mode })`. The stage is any positioned element; the
// effect fills it and scales its pixel values to the stage width, so the same
// code runs in the full demo, in small card previews, and on a client's site.
// `mode` is "live" (interactive / animated) or "still" (one static frame).

export const REFERENCE_WIDTH = 1000;

const fontRequests = new Map();

// Loads a Google Fonts stylesheet once and resolves when the family is ready.
export function loadFont(href, family, weight = "400") {
  if (!href || typeof document === "undefined") return Promise.resolve();
  const key = `${family}:${weight}`;
  if (fontRequests.has(key)) return fontRequests.get(key);
  // The @font-face rules exist only after the stylesheet loads, so wait for
  // it before asking the browser to fetch the font itself.
  let link = document.querySelector(`link[href="${href}"]`);
  const stylesheet = link && link.sheet ? Promise.resolve() : new Promise((resolve) => {
    if (!link) {
      link = document.createElement("link");
      link.rel = "stylesheet";
      link.href = href;
      document.head.append(link);
    }
    link.addEventListener("load", resolve, { once: true });
    link.addEventListener("error", resolve, { once: true });
  });
  const request = stylesheet
    .then(() => (document.fonts ? document.fonts.load(`${weight} 32px "${family}"`) : null))
    .catch(() => {})
    .then(() => undefined);
  fontRequests.set(key, request);
  return request;
}

export function loadFonts(fonts = []) {
  return Promise.all(fonts.map((font) => loadFont(font.href, font.family, font.weight)));
}

// Adds a stylesheet for an effect once per document.
export function injectStyle(id, css) {
  if (typeof document === "undefined" || document.getElementById(id)) return;
  const style = document.createElement("style");
  style.id = id;
  style.textContent = css;
  document.head.append(style);
}

// Pixel values in settings are authored for a 1000px-wide stage.
export function stageUnit(stage) {
  return (stage.clientWidth || REFERENCE_WIDTH) / REFERENCE_WIDTH;
}

// Every effect keeps the same margin inside its stage: 8% of the stage width.
export const SAFE_AREA = 0.08;

export function safeArea(stage) {
  const pad = Math.round(stage.clientWidth * SAFE_AREA);
  return {
    pad,
    width: Math.max(1, stage.clientWidth - pad * 2),
    height: Math.max(1, stage.clientHeight - pad * 2)
  };
}

// Scale that fits a box of the given size into the safe area. Previews pass
// `grow` so every card fills its safe area the same way; the full demo only
// shrinks content that would otherwise overflow. `fill` lets a preview whose
// type reads heavy take less of the area than the others.
export function fitScale(stage, width, height, { grow = false, fill = 1 } = {}) {
  if (!width || !height) return 1;
  const area = safeArea(stage);
  const scale = Math.min(area.width / width, area.height / height);
  return grow ? scale * fill : Math.min(1, scale);
}

// Fits an element by its layout size (transforms do not affect offset sizes)
// and writes the result to its `--fx-fit` custom property.
export function fitElement(stage, element, options) {
  const scale = fitScale(stage, element.offsetWidth, element.offsetHeight, options);
  element.style.setProperty("--fx-fit", scale.toFixed(4));
  return scale;
}

export function watchSize(stage, callback) {
  if (typeof ResizeObserver === "undefined") return () => {};
  let width = stage.clientWidth;
  let height = stage.clientHeight;
  const observer = new ResizeObserver(() => {
    if (stage.clientWidth === width && stage.clientHeight === height) return;
    width = stage.clientWidth;
    height = stage.clientHeight;
    callback();
  });
  observer.observe(stage);
  return () => observer.disconnect();
}

export function localPoint(stage, event) {
  const rect = stage.getBoundingClientRect();
  return { x: event.clientX - rect.left, y: event.clientY - rect.top };
}

let uid = 0;
export function uniqueId(prefix) {
  uid += 1;
  return `${prefix}-${uid}`;
}

// Splits text into words and letters without touching the original string.
export function splitWords(text) {
  return String(text).trim().split(/\s+/).filter(Boolean);
}

export function isHexColor(value) {
  return /^#[0-9a-f]{6}$/i.test(String(value));
}
```

## fade-in-blur.js

```js
import { fitElement, injectStyle, loadFonts, safeArea, splitWords, stageUnit, watchSize } from "./shared.js";

export const meta = {
  slug: "fade-in-blur",
  description: "Fade In With Blur is a text entrance where words emerge from a blur one after another.",
  title: "Fade In With Blur",
  codepen: "https://codepen.io/divulture/pen/LEYPNay",
  replay: true,
  fonts: [{ family: "Lexend", weight: "700", href: "https://fonts.googleapis.com/css2?family=Lexend:wght@700&display=swap" }],
  controls: [
    { key: "text", label: "Text", type: "text", maxlength: 60 },
    { key: "size", label: "Size", type: "range", min: 80, max: 320, step: 4, unit: "px" },
    { key: "blur", label: "Blur", type: "range", min: 0, max: 40, step: 1, unit: "px" },
    { key: "duration", label: "Duration", type: "range", min: 300, max: 4000, step: 100, unit: "ms" },
    { key: "stagger", label: "Stagger", type: "range", min: 0, max: 500, step: 10, unit: "ms" },
    { key: "textColor", label: "Text color", type: "color" },
    { key: "background", label: "Background", type: "color" }
  ],
  defaults: {
    text: "Fade in with blur",
    size: 224,
    blur: 10,
    duration: 1500,
    stagger: 100,
    textColor: "#FF4552",
    background: "#EFE8D8"
  }
};

const CSS = `
.fx-fade { position: absolute; inset: 0; display: grid; place-items: center; overflow: hidden; background: var(--fx-bg); color: var(--fx-fg); }
.fx-fade__text { width: max-content; margin: 0; text-wrap: balance; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) scale(var(--fx-fit, 1)); font-family: "Lexend", sans-serif; font-weight: 700; line-height: .9; }
.fx-fade__word { display: inline-block; }
.fx-fade[data-state="ready"] .fx-fade__word { opacity: 0; filter: blur(var(--fx-blur)); }
.fx-fade[data-state="play"] .fx-fade__word { opacity: 0; filter: blur(var(--fx-blur)); animation: fx-fade-in var(--fx-duration) forwards var(--fx-delay); }
@keyframes fx-fade-in { to { opacity: 1; filter: blur(0); } }
`;

export function mount(stage, initialSettings, { mode = "live", preview = false } = {}) {
  injectStyle("fx-fade-style", CSS);
  let settings = { ...meta.defaults, ...initialSettings };
  const root = document.createElement("div");
  root.className = "fx-fade";
  if (mode === "live") root.dataset.state = "ready";
  const text = document.createElement("p");
  text.className = "fx-fade__text";
  root.append(text);
  stage.append(root);

  function render() {
    const unit = stageUnit(stage);
    root.style.setProperty("--fx-bg", settings.background);
    root.style.setProperty("--fx-fg", settings.textColor);
    root.style.setProperty("--fx-blur", `${settings.blur * unit}px`);
    root.style.setProperty("--fx-duration", `${settings.duration}ms`);
    text.style.fontSize = `${settings.size * unit}px`;
    text.style.letterSpacing = `${-settings.size * unit * .045}px`;
    const words = splitWords(settings.text);
    text.replaceChildren();
    words.forEach((value, index) => {
      const word = document.createElement("span");
      word.className = "fx-fade__word";
      word.textContent = value;
      word.style.setProperty("--fx-delay", `${index * settings.stagger}ms`);
      text.append(word);
      if (index < words.length - 1) text.append(" ");
    });
    // Two lines at most: the text keeps one line while it fits the safe area,
    // otherwise it breaks near the middle instead of trailing a short line.
    text.style.maxWidth = "none";
    text.style.whiteSpace = "nowrap";
    const singleLine = text.offsetWidth;
    text.style.whiteSpace = "";
    const area = safeArea(stage);
    text.style.maxWidth = singleLine <= area.width ? "none" : `${Math.ceil((singleLine / 2) * 1.06)}px`;
    // the heavy two-line setting fills the card more than the other previews
    fitElement(stage, text, { grow: preview, fill: .8 });
  }

  // Each word sharpens from a blur with a small delay after the previous one.
  function play() {
    if (mode !== "live") return;
    root.dataset.state = "ready";
    void root.offsetWidth;
    root.dataset.state = "play";
  }

  const stopWatching = watchSize(stage, render);
  render();
  loadFonts(meta.fonts).then(() => {
    render();
    play();
  });

  return {
    update(next) {
      settings = { ...settings, ...next };
      render();
      play();
    },
    replay: play,
    destroy() {
      stopWatching();
      root.remove();
    }
  };
}
```
