# OTP Input

> A one-time code field: one real input drawn as cells. Digits rise into place, paste and SMS autofill just work, and the cells turn to ink once complete.

Forms · otp, code, input, form · HTML, CSS, vanilla JS · no dependencies · updated 2026-10-16
Demo: https://kodza.dev/components/otp-input/

## Files

The code below, served as files: byte for byte what the Kodza site copies (the CSS includes its theme guard).

- [`kodza-otp-input.css`](https://kodza.dev/registry/otp-input/kodza-otp-input.css) · 10.5 KB
- [`kodza-otp-input.js`](https://kodza.dev/registry/otp-input/kodza-otp-input.js) · 6.3 KB
- [`kodza-otp-input.html`](https://kodza.dev/registry/otp-input/kodza-otp-input.html) · 0.6 KB · the markup, to adapt and paste into your page

**Can you run shell commands? Download the CSS and the JS, don't retype them.** Retyping costs thousands of tokens and can drop or change lines of the CSS. Put the files where your stack expects them (Use it says where: change the `-o` paths):

```bash
curl -fsSL --create-dirs -o kodza/kodza-otp-input.css https://kodza.dev/registry/otp-input/kodza-otp-input.css
curl -fsSL --create-dirs -o kodza/kodza-otp-input.js https://kodza.dev/registry/otp-input/kodza-otp-input.js
```

Then load the files from your page as Use it shows, instead of pasting the content. The HTML is the part you adapt (text, links, modifiers): paste it from the Code section. Copy the CSS and the JS from the Code section only if you can't run commands, exactly as they are. (Windows PowerShell: `curl.exe`.)

## API

- Root: `.kodza-otp`
- Variables (set them on the root element itself: it declares its own defaults):
  - `--kz-otp-bg: #ffffff`
  - `--kz-otp-fg: #0a0a0a`
  - `--kz-otp-muted: rgba(10, 10, 10, 0.6)`
  - `--kz-otp-line: rgba(10, 10, 10, 0.14)`
  - `--kz-otp-soft: rgba(10, 10, 10, 0.06)`
  - `--kz-otp-ink: #0a0a0a`
  - `--kz-otp-on-ink: #ffffff`
  - `--kz-otp-cell: 52px`
  - `--kz-otp-height: 60px`
  - `--kz-otp-gap: 8px`
  - `--kz-otp-radius: 12px`
  - `--kz-otp-ease: cubic-bezier(0.22, 1, 0.36, 1)`
- Attributes:
  - `data-done`
  - `data-length` (e.g. `6`)
  - `data-resend`
- Events: `kodza:complete`, `kodza:resend` (bubbling, from the root)
- Lifecycle: `kodza:init` / `kodza:destroy` on `document`, with `{ detail: { root } }` to target a container.

## Keyboard

What each key does, by where the focus is. Keep it working when you adapt the HTML: same elements, same classes.

- In the code field (focus in `.kodza-otp__input`):
  - a letter: Only digits get in, one cell each
  - `Backspace`: Erases the last digit
  - `ArrowLeft` / `ArrowRight` / `Home` / `End`: Held back, the caret stays after the last digit

## Dark mode

The values Kodza uses on a dark background (`#0a0a0a`). For a page that follows the system theme, add them after the component's CSS:

```css
@media (prefers-color-scheme: dark) {
  .kodza-otp {
    --kz-otp-bg: #161616;
    --kz-otp-fg: #f2f2f0;
    --kz-otp-muted: rgba(242, 242, 240, 0.62);
    --kz-otp-line: rgba(255, 255, 255, 0.14);
    --kz-otp-soft: rgba(255, 255, 255, 0.08);
    --kz-otp-ink: #f2f2f0;
    --kz-otp-on-ink: #0a0a0a;
  }
}
```

A site with its own theme switch puts the same rules under its dark selector instead (`[data-theme="dark"] .kodza-otp { … }`); a single dark section, under that section's class.

## Use it

### Plain HTML page

- CSS: `kodza/kodza-otp-input.css` next to the page (the Files commands as they are), linked in `<head>`: `<link rel="stylesheet" href="kodza/kodza-otp-input.css">`. Without a shell, paste it in a `<style>` in `<head>` instead. It only touches `kodza-` classes.
- HTML: where the component goes. Paste it as many times as you need: instances never interfere.
- JS: `kodza/kodza-otp-input.js`, loaded with `<script src="kodza/kodza-otp-input.js" defer></script>` in `<head>`. Without a shell, paste it in a `<script>` before `</body>` (or in `<head>`: it waits for the page). One copy per page, whatever the number of instances.
- Restyle with the `--kz-…` variables, set on the component's root element itself (the root declares its own defaults, so a value on an ancestor is ignored), and with the modifiers / attributes listed under API.
- Font: it takes the page's own. The Kodza look is Geist: `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500&display=swap">`.
- Content added later (AJAX navigation, a SPA route, a builder preview): start it with `document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: container } }))`; before removing it, the same call with `'kodza:destroy'` stops it and puts the original markup back.

### Claude artifact (claude.ai)

- Paste the CSS in a `<style>` and the JS in a `<script>` at the end, in the artifact itself: it loads stylesheets only from Google Fonts and scripts only from a few CDNs, so no `<link>` or `<script src>` to Kodza.
- Writing the artifact file with a shell? Insert the downloaded files (Files) with a command instead of retyping them: a line `KODZA-CSS` alone inside the `<style>`, `KODZA-JS` inside the `<script>`, then `sed -e '/^KODZA-CSS$/{r kodza/kodza-otp-input.css' -e 'd' -e '}' -e '/^KODZA-JS$/{r kodza/kodza-otp-input.js' -e 'd' -e '}' page.html > artifact.html`.
- Font: load Geist from Google Fonts (allowed): `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500&display=swap">`.
- Dark mode: the viewer sets `data-theme="dark"` or `"light"` on `<html>`, or nothing when it follows the system. Write the Dark mode rules twice: inside `@media (prefers-color-scheme: dark)` with `:root:not([data-theme="light"])` in front of each selector, and with `:root[data-theme="dark"]` in front of each selector.
- Forms: there is nowhere to send them. Handle `submit` in your script with `event.preventDefault()` and show the result in the page.

### WordPress

- HTML: a **Custom HTML** block (or a pattern / template part). WordPress keeps this markup as it is only for users allowed to post unfiltered HTML (Administrators; Super Admins on multisite): for anyone else it strips tags such as `<svg>`, `<input>` or `<dialog>`, so add it from the theme (a pattern or template part) instead.
- CSS and JS: the downloaded files go in the theme, under `wp-content/themes/<your-theme>/kodza/` (the child theme if there is one), enqueued from its functions.php (or a code-snippets plugin):
  ```php
  add_action('wp_enqueue_scripts', function () {
    $dir = get_stylesheet_directory() . '/kodza/';
    $uri = get_stylesheet_directory_uri() . '/kodza/';
    wp_enqueue_style('kodza-otp-input', $uri . 'kodza-otp-input.css', [], filemtime($dir . 'kodza-otp-input.css'));
    wp_enqueue_script('kodza-otp-input', $uri . 'kodza-otp-input.js', [], filemtime($dir . 'kodza-otp-input.js'), true);
  });
  ```
  Scoped to `kodza-` classes, the CSS never touches the theme. One copy of the JS, whatever the number of blocks.
- No access to the theme files? The CSS can also go, as it is, in **Appearance → Customize → Additional CSS** (classic theme) or **Styles → Additional CSS** in the Site Editor (block theme).
- Theme with AJAX page transitions: fire `kodza:init` on the new content after each swap (and `kodza:destroy` on the old one).
- Performance plugin (WP Rocket, LiteSpeed Cache, Perfmatters…) with **Delay JavaScript execution** turned on: add `kodza` to the scripts it must not delay. Otherwise the component waits for the visitor's first scroll, tap or mouse move, and that first click can be lost.
- Colours: by default, match the theme's palette. After the component's CSS, point these variables at the theme's colours, on the component root, Kodza's value as the fallback:
  `.kodza-otp { --kz-otp-fg: var(TEXT, #0a0a0a); --kz-otp-bg: var(BACKGROUND, #ffffff); --kz-otp-ink: var(ACCENT, #0a0a0a); --kz-otp-on-ink: var(BACKGROUND, #ffffff); }`
  TEXT, BACKGROUND and ACCENT (the colour the theme fills its own buttons with) are the theme's own colour variables — block themes (theme.json, like Twenty Twenty-Five): `--wp--preset--color--contrast`, `--wp--preset--color--base`, `--wp--preset--color--contrast` (they fill their buttons with it; their accent-1… colours are decorative); Astra: `--ast-global-color-2`, `--ast-global-color-4`, `--ast-global-color-0`; Kadence: `--global-palette3`, `--global-palette9`, `--global-palette1`; GeneratePress: `--contrast`, `--base-3`, `--accent`; Blocksy: `--theme-palette-color-4`, `--theme-palette-color-8`, `--theme-palette-color-1`. Use only these names, and only if the site really has them (the theme's CSS, or Styles → Colors): the `--wp--preset--color--black`, `--white`, `--vivid-…` that WordPress adds everywhere are not the theme's palette. Another theme, or one without these variables (Hello Elementor, OceanWP): leave the variables alone, it keeps Kodza's monochrome; same when the developer asks for monochrome or the Kodza look. Leave the translucent greys (`rgba(10, 10, 10, …)`) as they are: they suit any light background. On a dark palette, set the other variables from Dark mode too.
- WordPress turns straight quotes and `--` into typographic ones in the text of a Custom HTML block (not inside `<code>` or `<pre>`).

#### With Elementor

- HTML: an **HTML** widget (Elementor shows it to administrators only). It keeps the code exactly as pasted, straight quotes included.
- CSS and JS: as above. Elementor's Site Settings → Theme Style styles every button, field, link and image of the page, components included; the theme guard at the end of the CSS keeps the component's buttons, fields and link colours as they are.
- The Elementor editor redraws each widget after the page has loaded: without the script below, the component stays still in the editor preview (the published page works). Add it once per site, in the footer like the component's script (`kodza/elementor-editor.js`, or a code-snippets plugin):

```js
// Kodza in the Elementor editor: the editor redraws each HTML widget after the page has loaded.
// Start Kodza in what it draws, stop it in what it replaces or removes. Once per site.
window.addEventListener('elementor/frontend/init', () => {
  if (!elementorFrontend.isEditMode()) return;
  class KodzaWidget extends elementorModules.frontend.handlers.Base {
    onInit() {
      super.onInit();
      this.kodza = [...this.$element[0].children];
      document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: this.$element[0] } }));
    }
    onDestroy() {
      super.onDestroy();
      this.kodza.forEach((root) => document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } })));
    }
  }
  elementorFrontend.elementsHandler.attachHandler('html', KodzaWidget);
});
```

- No child theme: everything can go in the HTML widget instead, `<style>` with the CSS, the HTML, then `<script>` with the JS. It works on the page and in the editor without the script above.

### Shopify

- Files: `assets/kodza-otp-input.css` and `assets/kodza-otp-input.js` (the Files commands with `-o assets/…`).
- In the section: `{{ 'kodza-otp-input.css' | asset_url | stylesheet_tag }}` and `<script src="{{ 'kodza-otp-input.js' | asset_url }}" defer></script>`, then the HTML.
- The theme editor re-renders sections: restart them with
  `document.addEventListener('shopify:section:load', (e) => document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: e.target } })));`
  and the same with `shopify:section:unload` → `kodza:destroy`.

### React / Next.js

- Files, side by side (e.g. in `components/kodza/`): `OTPInput.tsx` (below), the CSS block under Code saved as `otp-input.css` and the JS block as `otp-input.js`, both as they are. The HTML block is already inside the component: skip it.
- Use it: `import { OTPInput } from '@/components/kodza/OTPInput';` then `<OTPInput />`. Props: `length` (`data-length`: "6"), `vars` (the `--kz-…` variables listed under API, e.g. `vars={{ '--kz-otp-bg': … }}`), `onComplete` (the `kodza:complete` event), `onResend` (the `kodza:resend` event), `className`, `style` and the other props of its `<div>` (`onClick`, `aria-…`).
- Next.js App Router: it is a Client Component already (`'use client'`). Pages Router: Next.js takes global CSS only in `pages/_app`, so move the `import './otp-input.css'` line there.
- Safe under StrictMode, client-side navigation and prop changes: when a prop changes, the `key` gives React a fresh element, `kodza:destroy` stops the script on the old one and `kodza:init` starts it on the new one.

```tsx
'use client';
// Kodza — OTP Input, for React. From https://kodza.dev/components/otp-input/
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Next to this file: otp-input.css and otp-input.js, the component's CSS and JS from Kodza, as they are.
// Yours to edit: the markup is plain JSX below.
// The script changes this markup once React has rendered it (it adds layers, splits text, moves
// nodes), so React must not patch it afterwards. When a prop changes, the key gives React a fresh
// element: kodza:destroy stops the script on the old one, kodza:init starts it on the new one.
import { useRef, useEffect, type ComponentPropsWithoutRef, type ComponentRef, type CSSProperties } from 'react';
import './otp-input.css';

export type OTPInputProps = Omit<ComponentPropsWithoutRef<'div'>, "children" | "vars" | "length" | "onComplete" | "onResend"> & {
  /** data-length on the root (default: 6) */
  length?: "6";
  /** Settings, as CSS variables on the root */
  vars?: {
    /** default: #ffffff */
    "--kz-otp-bg"?: string | number;
    /** default: #0a0a0a */
    "--kz-otp-fg"?: string | number;
    /** default: rgba(10, 10, 10, 0.6) */
    "--kz-otp-muted"?: string | number;
    /** default: rgba(10, 10, 10, 0.14) */
    "--kz-otp-line"?: string | number;
    /** default: rgba(10, 10, 10, 0.06) */
    "--kz-otp-soft"?: string | number;
    /** default: #0a0a0a */
    "--kz-otp-ink"?: string | number;
    /** default: #ffffff */
    "--kz-otp-on-ink"?: string | number;
    /** default: 52px */
    "--kz-otp-cell"?: string | number;
    /** default: 60px */
    "--kz-otp-height"?: string | number;
    /** default: 8px */
    "--kz-otp-gap"?: string | number;
    /** default: 12px */
    "--kz-otp-radius"?: string | number;
    /** default: cubic-bezier(0.22, 1, 0.36, 1) */
    "--kz-otp-ease"?: string | number;
  };
  /** "kodza:complete", fired by the script (bubbles from the root) */
  onComplete?: (event: CustomEvent) => void;
  /** "kodza:resend", fired by the script (bubbles from the root) */
  onResend?: (event: CustomEvent) => void;
  className?: string;
};

export function OTPInput({ length = "6", vars, onComplete, onResend, className, style, ...rest }: OTPInputProps) {
  const ref = useRef<ComponentRef<'div'>>(null);
  const classes = ["kodza-otp", className].filter(Boolean).join(' ');
  // Everything the markup is made of: when it changes, React gets a fresh element (see the top)
  const key = JSON.stringify([classes, length, vars, style, rest]);

  // Starts the script on this element once React has rendered it, stops it when it goes
  useEffect(() => {
    const root = ref.current;
    let live = true;
    // @ts-ignore: a plain script, no types to find
    import('./otp-input.js').then(() => {
      if (live) document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root } }));
    });
    return () => {
      live = false;
      document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } }));
    };
  }, [key]);

  useEffect(() => {
    const root = ref.current;
    if (!root || !onComplete) return;
    const listener = (event: Event) => onComplete(event as CustomEvent);
    root.addEventListener("kodza:complete", listener);
    return () => root.removeEventListener("kodza:complete", listener);
  }, [onComplete, key]);

  useEffect(() => {
    const root = ref.current;
    if (!root || !onResend) return;
    const listener = (event: Event) => onResend(event as CustomEvent);
    root.addEventListener("kodza:resend", listener);
    return () => root.removeEventListener("kodza:resend", listener);
  }, [onResend, key]);

  return (
    <div key={key} {...rest} className={classes} data-length={length} style={{ ...vars, ...style } as CSSProperties} ref={ref}>
      <p className="kodza-otp__label">Enter the code we sent to florent@kodza.dev</p>
      <div className="kodza-otp__field">
        <input className="kodza-otp__input" type="text" inputMode="numeric" autoComplete="one-time-code" maxLength={6} aria-label="Six-digit code" />
        <div className="kodza-otp__cells" aria-hidden="true" />
      </div>
      <p className="kodza-otp__foot">
        <span className="kodza-otp__done" aria-live="polite" />
        {' '}
        <span className="kodza-otp__again">Didn't get it? <button className="kodza-otp__resend" type="button">Resend in <span className="kodza-otp__count">30</span>s</button></span>
      </p>
    </div>
  );
}
```

## Code

```html
<div class="kodza-otp" data-length="6">
  <p class="kodza-otp__label">Enter the code we sent to florent@kodza.dev</p>
  <div class="kodza-otp__field">
    <input class="kodza-otp__input" type="text" inputmode="numeric" autocomplete="one-time-code" maxlength="6" aria-label="Six-digit code">
    <div class="kodza-otp__cells" aria-hidden="true"></div>
  </div>
  <p class="kodza-otp__foot">
    <span class="kodza-otp__done" aria-live="polite"></span>
    <span class="kodza-otp__again">Didn't get it? <button class="kodza-otp__resend" type="button">Resend in <span class="kodza-otp__count">30</span>s</button></span>
  </p>
</div>
```

```css
/* Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license */
/* Kodza — OTP Input
   A one-time code field: one real input (so paste, SMS autofill and screen readers just work)
   drawn as separate cells. Each digit rises into its cell from behind a mask, the active cell
   shows a blinking caret, and once the code is complete the cells turn to ink one after the
   other. The resend link counts down before it wakes up.
   Everything is tuned with the --kz-otp-* variables. */
.kodza-otp {
  --kz-otp-bg: #ffffff;
  --kz-otp-fg: #0a0a0a;
  --kz-otp-muted: rgba(10, 10, 10, 0.6);
  --kz-otp-line: rgba(10, 10, 10, 0.14);
  --kz-otp-soft: rgba(10, 10, 10, 0.06);
  --kz-otp-ink: #0a0a0a;
  --kz-otp-on-ink: #ffffff;
  --kz-otp-cell: 52px;
  --kz-otp-height: 60px;
  --kz-otp-gap: 8px;
  --kz-otp-radius: 12px;
  --kz-otp-ease: cubic-bezier(0.22, 1, 0.36, 1);

  display: grid;
  justify-items: start;
  gap: 14px;
  color: var(--kz-otp-fg);
}

.kodza-otp__label {
  margin: 0;
  font-size: 15px;
  font-weight: 500;
}

.kodza-otp__field {
  position: relative;
}

/* The real input covers the cells, invisible: it takes the typing, the paste and the focus */
.kodza-otp__input {
  position: absolute;
  inset: 0;
  z-index: 1;
  width: 100%;
  height: 100%;
  padding: 0;
  border: 0;
  background: transparent;
  color: transparent;
  caret-color: transparent;
  font-size: 16px;
  letter-spacing: 3em;
  outline: none;
  opacity: 0.01;
}

.kodza-otp__cells {
  display: flex;
  align-items: center;
  gap: var(--kz-otp-gap);
}

.kodza-otp__cell {
  position: relative;
  display: grid;
  place-items: center;
  width: var(--kz-otp-cell);
  height: var(--kz-otp-height);
  overflow: hidden;
  border-radius: var(--kz-otp-radius);
  background: var(--kz-otp-bg);
  box-shadow: inset 0 0 0 1px var(--kz-otp-line);
  font-size: 24px;
  font-weight: 600;
  font-variant-numeric: tabular-nums;
  transition: box-shadow 0.2s ease;
}

/* The ink that fills the cell from the bottom once the code is complete: it carries a white
   copy of the digit, so the digit turns white exactly where the ink reaches it */
.kodza-otp__cell::before {
  content: attr(data-digit);
  position: absolute;
  inset: 0;
  z-index: 1;
  display: grid;
  place-items: center;
  background: var(--kz-otp-ink);
  color: var(--kz-otp-on-ink);
  clip-path: inset(100% 0 0 0);
  transition: clip-path 0.45s cubic-bezier(0.65, 0, 0.35, 1);
}

.kodza-otp__cell > span {
  grid-area: 1 / 1;
}

/* A new digit rises into its cell */
.kodza-otp__cell > span.is-new {
  animation: kodza-otp-in 0.4s var(--kz-otp-ease);
}

@keyframes kodza-otp-in {
  from {
    transform: translateY(100%);
  }
}

/* The cell waiting for the next digit, while the field has the focus */
.kodza-otp__field:focus-within .kodza-otp__cell.is-active {
  box-shadow: inset 0 0 0 1.5px var(--kz-otp-fg), 0 0 0 4px var(--kz-otp-soft);
}

.kodza-otp__field:focus-within .kodza-otp__cell.is-active::after {
  content: "";
  position: absolute;
  top: 50%;
  left: 50%;
  width: 1.5px;
  height: 24px;
  background: var(--kz-otp-fg);
  transform: translate(-50%, -50%);
  animation: kodza-otp-caret 1s steps(2, jump-none) infinite;
}

@keyframes kodza-otp-caret {
  50% {
    opacity: 0;
  }
}

.kodza-otp__sep {
  width: 10px;
  height: 2px;
  margin: 0 2px;
  border-radius: 2px;
  background: var(--kz-otp-line);
}

/* Complete: ink rises in each cell, one after the other */
.kodza-otp.is-done .kodza-otp__cell {
  box-shadow: none;
  transition: box-shadow 0.2s ease calc(var(--i, 0) * 60ms + 0.3s);
}

.kodza-otp.is-done .kodza-otp__cell::before {
  clip-path: inset(0);
  transition-delay: calc(var(--i, 0) * 60ms);
}

/* The foot: the resend line, then the done message, in one cell */
.kodza-otp__foot {
  display: grid;
  margin: 0;
  font-size: 13px;
  color: var(--kz-otp-muted);
}

.kodza-otp__done,
.kodza-otp__again {
  grid-area: 1 / 1;
  transition: opacity 0.25s ease, transform 0.4s var(--kz-otp-ease);
}

.kodza-otp__done {
  color: var(--kz-otp-fg);
  font-weight: 500;
  opacity: 0;
  transform: translateY(8px);
}

.kodza-otp.is-done .kodza-otp__done {
  opacity: 1;
  transform: none;
  transition-delay: 0.35s;
}

.kodza-otp.is-done .kodza-otp__again {
  opacity: 0;
  transform: translateY(-8px);
  visibility: hidden;
}

.kodza-otp__resend {
  padding: 0;
  border: 0;
  border-radius: 4px;
  background: none;
  color: var(--kz-otp-fg);
  font: inherit;
  font-weight: 500;
  text-decoration: underline;
  text-underline-offset: 3px;
  cursor: pointer;
}

.kodza-otp__resend:disabled {
  color: var(--kz-otp-muted);
  text-decoration: none;
  cursor: default;
}

.kodza-otp__resend:focus-visible {
  outline: 2px solid var(--kz-otp-fg);
  outline-offset: 2px;
}

.kodza-otp__count {
  display: inline-grid;
  overflow: hidden;
  font-family: ui-monospace, "SF Mono", Menlo, monospace;
  font-variant-numeric: tabular-nums;
  vertical-align: bottom;
}

.kodza-otp__count > span {
  grid-area: 1 / 1;
}

@media (max-width: 420px) {
  .kodza-otp {
    --kz-otp-cell: 42px;
    --kz-otp-height: 52px;
    --kz-otp-gap: 6px;
  }
}

@media (prefers-reduced-motion: reduce) {
  .kodza-otp__cell > span.is-new,
  .kodza-otp__field:focus-within .kodza-otp__cell.is-active::after {
    animation: none;
  }

  .kodza-otp__cell,
  .kodza-otp__cell::before,
  .kodza-otp.is-done .kodza-otp__cell,
  .kodza-otp__done,
  .kodza-otp__again {
    transition-duration: 0.01ms !important;
    transition-delay: 0s !important;
  }
}

/* Theming example — on a dark background:
.dark-section .kodza-otp {
  --kz-otp-bg: #161616;
  --kz-otp-fg: #f2f2f0;
  --kz-otp-muted: rgba(242, 242, 240, 0.62);
  --kz-otp-line: rgba(255, 255, 255, 0.14);
  --kz-otp-soft: rgba(255, 255, 255, 0.08);
  --kz-otp-ink: #f2f2f0;
  --kz-otp-on-ink: #0a0a0a;
}
*/

/* kodza-guard d1c178b448b0 — generated by Kodza, do not edit.
   Theme guard: keeps a site's own CSS (WordPress themes, Bootstrap, CSS resets…) off this
   component. :not(#_) is always true and weighs as much as an id, so these lines win over
   theme rules made of classes and tags. Customise the component through its --kz-* variables. */

/* What the browser gives, where the component sets it only in some states: at the lowest weight, so its own rules below put it back */

:where(.kodza-otp__resend):not(#_) {
  outline: revert;
  outline-offset: revert;
}

/* What the browser gives, on everything the component leaves to it */

.kodza-otp:not(#_),
.kodza-otp__field:not(#_),
.kodza-otp__cells:not(#_),
.kodza-otp__cell:not(#_),
.kodza-otp__sep:not(#_),
.kodza-otp__done:not(#_),
.kodza-otp__again:not(#_),
.kodza-otp__count:not(#_),
.kodza-otp__count span:where(:not([class*="kodza-"])):not(#_) {
  box-sizing: revert;
}

.kodza-otp__label:not(#_) {
  border: revert;
  padding: revert;
  border-radius: revert;
  outline: revert;
  text-decoration: revert;
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  float: revert;
  position: revert;
  background-color: revert;
  background-image: revert;
  box-shadow: revert;
  outline-offset: revert;
  appearance: revert;
  max-width: revert;
  max-height: revert;
  color: revert;
  font-family: revert;
  font-style: revert;
  line-height: revert;
  letter-spacing: revert;
  text-transform: revert;
  text-underline-offset: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
}

.kodza-otp__input:not(#_) {
  margin: revert;
  border-radius: revert;
  text-decoration: revert;
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  float: revert;
  box-shadow: revert;
  outline-offset: revert;
  appearance: revert;
  max-width: revert;
  max-height: revert;
  font-family: revert;
  font-weight: revert;
  font-style: revert;
  line-height: revert;
  text-transform: revert;
  text-underline-offset: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
  white-space: revert;
  min-height: revert;
}

.kodza-otp__foot:not(#_) {
  border: revert;
  padding: revert;
  border-radius: revert;
  outline: revert;
  text-decoration: revert;
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  float: revert;
  position: revert;
  background-color: revert;
  background-image: revert;
  box-shadow: revert;
  outline-offset: revert;
  appearance: revert;
  max-width: revert;
  max-height: revert;
  font-family: revert;
  font-weight: revert;
  font-style: revert;
  line-height: revert;
  letter-spacing: revert;
  text-transform: revert;
  text-underline-offset: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
}

.kodza-otp__resend:not(#_) {
  margin: revert;
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  float: revert;
  position: revert;
  box-shadow: revert;
  appearance: revert;
  max-width: revert;
  max-height: revert;
  letter-spacing: revert;
  text-transform: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
  white-space: revert;
  min-height: revert;
}

.kodza-otp__label:not(#_):where(:not([hidden])),
.kodza-otp__input:not(#_):where(:not([hidden])),
.kodza-otp__resend:not(#_):where(:not([hidden])) {
  display: revert;
}

.kodza-otp__label:not(#_):where([hidden]),
.kodza-otp__input:not(#_):where([hidden]),
.kodza-otp__resend:not(#_):where([hidden]) {
  display: none;
}

.kodza-otp__cell:not(#_)::before,
.kodza-otp__cell:not(#_)::after {
  box-sizing: revert;
}

/* The component's own rules, one step stronger: real buttons and fields, what it sets on tags themes style (links, lists, headings, images…), and the root width (a theme may narrow it, never widen it) */

.kodza-otp__label:not(#_) {
  margin: 0;
  font-size: 15px;
  font-weight: 500;
}

.kodza-otp__input:not(#_) {
  position: absolute;
  inset: 0;
  z-index: 1;
  width: 100%;
  height: 100%;
  padding: 0;
  border: 0;
  background: transparent;
  color: transparent;
  caret-color: transparent;
  font-size: 16px;
  letter-spacing: 3em;
  outline: none;
  opacity: 0.01;
}

.kodza-otp__foot:not(#_) {
  display: grid;
  margin: 0;
  font-size: 13px;
  color: var(--kz-otp-muted);
}

.kodza-otp__resend:not(#_) {
  padding: 0;
  border: 0;
  border-radius: 4px;
  background: none;
  color: var(--kz-otp-fg);
  font: inherit;
  font-weight: 500;
  text-decoration: underline;
  text-underline-offset: 3px;
  cursor: pointer;
}

.kodza-otp__resend:disabled:not(#_) {
  color: var(--kz-otp-muted);
  text-decoration: none;
  cursor: default;
}

.kodza-otp__resend:focus-visible:not(#_) {
  outline: 2px solid var(--kz-otp-fg);
  outline-offset: 2px;
}
```

```js
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Kodza — OTP Input
// Draws the cells (a dash in the middle), keeps the input to digits, shows each digit in its
// cell (the new one rising), marks the cell waiting for the next one, and plays the "done"
// state once the code is complete. Fires "kodza:complete" with { code }. The resend button
// counts down from data-resend seconds (30) before it can be used, and fires "kodza:resend".
(() => {
  const SELECTOR = '.kodza-otp';
  const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  // One instance. Everything it starts is tied to `signal`, so kodza:destroy stops it all
  function mount(root, signal) {
    const input = root.querySelector('.kodza-otp__input');
    const box = root.querySelector('.kodza-otp__cells');
    const done = root.querySelector('.kodza-otp__done');
    const resend = root.querySelector('.kodza-otp__resend');
    const count = root.querySelector('.kodza-otp__count');
    if (!input || !box) return;
    const length = Number(root.dataset.length) || Number(input.maxLength) || 6;
    input.maxLength = length;

    const cells = Array.from({ length }, (_, i) => {
      const cell = document.createElement('span');
      cell.className = 'kodza-otp__cell';
      cell.style.setProperty('--i', i);
      return cell;
    });
    const half = Math.floor(length / 2);
    box.append(...cells.slice(0, half), Object.assign(document.createElement('span'), { className: 'kodza-otp__sep' }), ...cells.slice(half));

    let shown = '';
    const render = () => {
      const value = input.value.replace(/\D/g, '').slice(0, length);
      if (value !== input.value) input.value = value;
      cells.forEach((cell, i) => {
        const digit = value[i] || '';
        if (digit !== (shown[i] || '')) {
          const span = document.createElement('span');
          span.textContent = digit;
          if (digit && !reduceMotion) span.classList.add('is-new');
          cell.replaceChildren(span);
          cell.dataset.digit = digit;
        }
        cell.classList.toggle('is-active', i === Math.min(value.length, length - 1) && value.length < length);
      });
      const complete = value.length === length;
      if (complete && !root.classList.contains('is-done')) {
        root.classList.add('is-done');
        if (done) done.textContent = root.dataset.done || 'Code accepted. Welcome back.';
        root.dispatchEvent(new CustomEvent('kodza:complete', { detail: { code: value }, bubbles: true }));
      } else if (!complete) {
        root.classList.remove('is-done');
        if (done) done.textContent = '';
      }
      shown = value;
    };
    input.addEventListener('input', render, { signal });
    // The caret always sits at the end: the cells read left to right
    const end = () => input.setSelectionRange(input.value.length, input.value.length);
    input.addEventListener('focus', () => requestAnimationFrame(end), { signal });
    input.addEventListener('click', end, { signal });
    input.addEventListener('keydown', (event) => ['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key) && event.preventDefault(), { signal });

    // Resend: a countdown that rolls, then a link
    const seconds = Number(root.dataset.resend) || 30;
    let left = 0;
    let timer = 0;
    const roll = (value) => {
      if (!count) return;
      const prev = count.lastElementChild;
      const span = Object.assign(document.createElement('span'), { textContent: value });
      count.append(span);
      if (!prev) return;
      if (reduceMotion) return prev.remove();
      const timing = { duration: 350, easing: 'cubic-bezier(0.22, 1, 0.36, 1)' };
      prev.animate([{ transform: 'none' }, { transform: 'translateY(-110%)' }], { ...timing, fill: 'forwards' }).finished.then(() => prev.remove());
      span.animate([{ transform: 'translateY(110%)' }, { transform: 'none' }], timing);
    };
    const tick = () => {
      left -= 1;
      if (left <= 0) {
        clearInterval(timer);
        resend.disabled = false;
        resend.replaceChildren('Resend code');
        return;
      }
      roll(left);
    };
    const start = () => {
      if (!resend) return;
      left = seconds;
      resend.disabled = true;
      if (count) {
        count.replaceChildren();
        roll(left);
        resend.replaceChildren('Resend in ', count, 's');
      }
      clearInterval(timer);
      timer = setInterval(tick, 1000);
    };
    signal.addEventListener('abort', () => clearInterval(timer));
    resend?.addEventListener('click', () => {
      root.dispatchEvent(new CustomEvent('kodza:resend', { bubbles: true }));
      start();
      input.focus();
    }, { signal });

    render();
    start();
  }

  // Kodza lifecycle, the same in every component: `kodza:init` starts the instances inside
  // event.detail.root (the whole page by default), `kodza:destroy` stops them and puts their
  // markup back. For themes and apps that swap content without a page load.
  const instances = new WeakMap();
  const find = (scope = document) => [scope, ...scope.querySelectorAll(SELECTOR)].filter((el) => el.matches?.(SELECTOR));
  const init = (scope) => find(scope).forEach((root) => {
    if (root.classList.contains('is-ready')) return; // already running, maybe from another copy of this script
    const controller = new AbortController();
    instances.set(root, { controller, html: root.innerHTML, attrs: [...root.attributes].map((a) => [a.name, a.value]) });
    mount(root, controller.signal);
    root.classList.add('is-ready');
  });
  const destroy = (scope) => find(scope).forEach((root) => {
    const instance = instances.get(root);
    if (!instance) return;
    instances.delete(root);
    instance.controller.abort();
    [...root.attributes].forEach((a) => root.removeAttribute(a.name));
    instance.attrs.forEach(([name, value]) => root.setAttribute(name, value));
    root.innerHTML = instance.html;
  });
  document.addEventListener('kodza:init', (event) => init(event.detail?.root));
  document.addEventListener('kodza:destroy', (event) => destroy(event.detail?.root));
  init();
  // Loaded in <head>, the script runs before the markup exists: once more when it is parsed
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => init(), { once: true });
})();
```

Free to use, from Kodza (https://kodza.dev).
