Elastic slider
A native slider with a yielding track, live value and keyboard reachable preset stops.
pnpm dlx shadcn@latest add @haze/elastic-slider---
import { cn } from "../../../lib/haze/utils";
import Slider from "./slider.astro";
interface Props {
id: string;
name?: string;
label?: string;
min?: number;
max?: number;
step?: number;
value?: number;
unit?: string;
marks?: { value: number; label: string }[];
disabled?: boolean;
class?: string;
[key: string]: unknown;
}
const { id, name = id, label = "Playback volume", min = 0, max = 100, step = 1, value = 60, unit = "%", marks = [{ value: 0, label: "Mute" }, { value: 50, label: "Half" }, { value: 100, label: "Full" }], disabled, class: className, ...rest } = Astro.props;
const floor = Number.isFinite(min) ? min : 0;
const ceiling = Number.isFinite(max) && max > floor ? max : floor + 100;
const increment = Number.isFinite(step) && step > 0 ? step : 1;
const initial = Number.isFinite(value) ? Math.max(floor, Math.min(ceiling, value)) : floor;
const stops = marks.filter((mark) => Number.isFinite(mark.value) && mark.value >= floor && mark.value <= ceiling);
---
<div data-haze-elastic-slider data-unit={unit} class={cn("grid w-full min-w-0 gap-3 text-foreground", className)}>
<div class="flex flex-wrap items-baseline justify-between gap-2">
<label for={id} class="text-[0.8125rem]/5 font-medium">{label}</label>
<output data-readout for={id} aria-hidden="true" class="text-[0.8125rem]/5 text-muted-foreground tabular-nums">{initial}{unit}</output>
</div>
<div data-elastic-track class="translate-x-(--elastic-offset,0px) transition-[translate] duration-200 ease-snappy data-[dragging]:duration-75">
<Slider id={id} name={name} min={floor} max={ceiling} step={increment} value={initial} disabled={disabled} list={`${id}-stops`} {...rest} />
</div>
<datalist id={`${id}-stops`}>{stops.map((mark) => <option value={mark.value} label={mark.label} />)}</datalist>
<div class="flex flex-wrap justify-between gap-1">
{stops.map((mark) => <button type="button" data-stop={mark.value} disabled class="min-h-8 cursor-pointer rounded-md px-1.5 text-[0.8125rem]/5 text-muted-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75 disabled:cursor-default">{mark.label}</button>)}
</div>
</div>
<script>
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const input = root.querySelector<HTMLInputElement>("input[type=range]");
const track = root.querySelector<HTMLElement>("[data-elastic-track]");
const readout = root.querySelector<HTMLOutputElement>("[data-readout]");
if (!input || !track || !readout) return;
const reduced = matchMedia("(prefers-reduced-motion: reduce)");
const stops = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-stop]"));
let pointer: number | null = null;
const sync = () => {
readout.textContent = `${input.value}${root.dataset.unit || ""}`;
input.setAttribute("aria-valuetext", readout.textContent);
stops.forEach((button) => { button.disabled = input.disabled; button.setAttribute("aria-pressed", String(Number(button.dataset.stop) === input.valueAsNumber)); });
};
const release = () => { pointer = null; track.removeAttribute("data-dragging"); track.style.setProperty("--elastic-offset", "0px"); };
input.addEventListener("pointerdown", (event) => { if (!input.disabled) { pointer = event.pointerId; track.setAttribute("data-dragging", ""); } });
input.addEventListener("pointermove", (event) => {
if (pointer !== event.pointerId || reduced.matches) return;
const rect = input.getBoundingClientRect();
const overflow = event.clientX < rect.left ? event.clientX - rect.left : event.clientX > rect.right ? event.clientX - rect.right : 0;
track.style.setProperty("--elastic-offset", `${Math.sign(overflow) * Math.min(8, Math.sqrt(Math.abs(overflow)))}px`);
});
["pointerup", "pointercancel", "lostpointercapture", "blur"].forEach((type) => input.addEventListener(type, release));
input.addEventListener("input", sync);
input.addEventListener("change", () => { release(); sync(); });
stops.forEach((button) => button.addEventListener("click", () => { input.value = button.dataset.stop!; input.dispatchEvent(new Event("input", { bubbles: true })); input.dispatchEvent(new Event("change", { bubbles: true })); input.focus(); }));
input.form?.addEventListener("reset", () => queueMicrotask(() => { release(); sync(); }));
root.setAttribute("data-enhanced", "");
sync();
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-elastic-slider]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-elastic-slider-listener")) {
document.documentElement.setAttribute("data-haze-elastic-slider-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- Volume, intensity or a similar continuous setting benefits from subtle resistance at the limits.
- A few common values should be reachable directly as named presets.
When not to use
- Use slider for a plain compact range without preset buttons.
- Use range-slider when users choose both bounds of an interval.
Installation
Add the Haze registry to components.json once, then install Elastic slider with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/elastic-slidernpx shadcn@latest add @haze/elastic-slideryarn dlx shadcn@latest add @haze/elastic-sliderbunx --bun shadcn@latest add @haze/elastic-sliderFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique caller supplied prefix for the control and its associated content. |
| name | string | id | Name submitted by the native form control. |
| label | string | Playback volume | Visible label for the range input. |
| min | number | 0 | Lower bound of the domain. |
| max | number | 100 | Upper bound of the domain. |
| step | number | 1 | Native range increment. |
| value | number | 60 | Initial setting, clamped to the supplied domain. |
| unit | string | % | Suffix used in the readout and accessible value. |
| marks | { value: number; label: string }[] | Mute / Half / Full | Named native datalist stops with enhanced shortcut buttons. |
| disabled | boolean | false | Prevents user changes through the native disabled state. |
| class | string | – | Additional classes on this component's outer wrapper. |
| [key: string] | unknown | – | Other native range attributes are passed through to Slider. |
Keyboard interactions
- ArrowsHomeEnd
- Adjust the native range or reach either end.
- Tab, EnterSpace
- Focus and apply one of the named stops.
Accessibility
- The real range input remains the only slider and provides native keyboard behavior and forced color support.
- The datalist works without enhancement; preset buttons are enabled only after their handlers are ready.
- The visible readout is hidden from assistive technology because aria-valuetext supplies the same value with its unit.
- Track displacement is capped at eight pixels and is skipped for reduced motion; cancellation releases the transient displacement.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Elastic slider" with `npx shadcn@latest add @haze/elastic-slider`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import ElasticSlider from "@/components/haze/ui/elastic-slider.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/elastic-slider.md
Customize with real content
Adapt the Haze elastic-slider ui for our product. Replace the demo values of these props with our real content: id, name, label, min, max, step, value, unit, marks, disabled, class, [key: string]. Keep the layout, the heading level rules and these accessibility details: The real range input remains the only slider and provides native keyboard behavior and forced color support. The datalist works without enhancement; preset buttons are enabled only after their handlers are ready. The visible readout is hidden from assistive technology because aria-valuetext supplies the same value with its unit. Track displacement is capped at eight pixels and is skipped for reduced motion; cancellation releases the transient displacement. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using elastic-slider, check it fits: use it when volume, intensity or a similar continuous setting benefits from subtle resistance at the limits.; a few common values should be reachable directly as named presets.. Avoid it when use slider for a plain compact range without preset buttons.; use range-slider when users choose both bounds of an interval.. Alternatives: @haze/slider, @haze/range-slider, @haze/ruler-slider.
Dependencies
- @haze/slider
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.