Skip to main content

Slider

Choose a number or range by moving one or more thumbs.

Volume60.00%
Props
Slots

Anatomy#

Slider [component; slot=root]
├── track [slot]
│   ├── range [slot]
│   └── marker [slot]
└── thumb [slot]

Usage#

Use Slider when a numeric value or range is best chosen spatially. Pair it with a labeled numeric field when users need precise text entry. Use NumberInput when the value is typed and stepped rather than dragged. Use BoldSlider for a compact single value with the label and value shown inside the track.

import { Field, Slider } from 'moraine'

export function Example() {
  return (
    <Field label="Volume">
      <Slider defaultValue={50} />
    </Field>
  )
}

Single values and ranges#

Use a number for one thumb and an array for one thumb per entry, such as an ordered pair for a range. Values are clamped to min–max (default 0–100), and arrays are sorted. Pair value with onValueChange for controlled state, or use defaultValue for uncontrolled state; its shape sets the shape of the value that callbacks receive.

onValueChange fires on every change during a drag, track click, or key press, but not for programmatic changes to value. Use onValueCommit to react once when the interaction ends, such as when saving a setting.

<Slider value={volume()} onValueChange={setVolume} />
<Slider value={range()} onValueChange={setRange} onValueCommit={saveRange} />

Step and markers#

Set step to snap pointer drag and keyboard navigation to multiples of it from min. Set markers to true to draw a tick at each step (this requires a step above 0), or to a number to draw a tick every that many units without changing how the value snaps.

<Slider value={value()} min={0} max={100} step={10} markers onValueChange={setValue} />
<Slider value={value()} min={0} max={100} markers={25} onValueChange={setValue} />

Value text format#

formatOptions accepts Intl.NumberFormat options and formats each thumb’s aria-valuetext with the provider locale. It does not change the value that callbacks receive. A percent style multiplies by 100, so pair it with a 0–1 range. BoldSlider also uses formatOptions for its visible value unless valueLabel is a formatter.

<Slider defaultValue={50} formatOptions={{ style: 'unit', unit: 'percent' }} aria-label="Zoom" />

Forms#

Add name for native form submission, or place the slider inside form.Field from createForm for schema binding. Use standalone Field when you only need a label and messages.

<Slider name="brightness" defaultValue={75} step={5} min={0} max={100} />

Custom content#

Pass children to render extra content inside the root after the thumbs. A render function receives the live value, sorted values, percentages from 0 to 1, dragging state, and the startEdge where the filled range begins. Declare the function’s parameter even when you do not use it; a zero-argument function is called as an accessor and is not mounted as a component.

<Slider defaultValue={40}>{(state) => <output>{state.value}</output>}</Slider>

Keyboard interaction#

When step is omitted, keyboard stepping defaults to 1% of the configured range. Page-sized movement is approximately 10% of the range and is snapped to step when one is defined. Horizontal arrow keys swap in right-to-left layouts, and a reversed vertical slider swaps ↑ and ↓.

Key Description
→ / ↑ Moves in the increasing direction by one keyboard step.
← / ↓ Moves in the decreasing direction by one keyboard step.
Shift + Arrow Moves by the page-sized increment.
⇞ / ⇟ Moves by the page-sized increment.
↖ Moves the focused thumb to its minimum permitted value.
↘ Moves the focused thumb to its maximum permitted value.

Examples#

Control output volume#

Keep a single number in local state and update it from onValueChange. Mute can write 0 back into the same signal.

import { Button, Icon, Slider } from 'moraine'
import { createSignal } from 'solid-js'

export function ControlledSingle() {
  const [volume, setVolume] = createSignal(75)

  const volumeIcon = () => {
    if (volume() === 0) {
      return 'i-lucide:volume-x'
    }
    if (volume() < 50) {
      return 'i-lucide:volume-1'
    }
    return 'i-lucide:volume-2'
  }

  return (
    <div class="p-4 b-1 b-border rounded-xl max-w-md w-full space-y-2">
      <div class="flex items-center justify-between">
        <div class="flex gap-2 items-center">
          <Button
            variant="ghost"
            size="sm"
            class="p-0 size-8"
            onClick={() => setVolume((v) => (v === 0 ? 75 : 0))}
            aria-label="Mute / Unmute"
          >
            <Icon name={volumeIcon()} class="size-4" />
          </Button>
          <span class="text-sm font-medium">Output Volume</span>
        </div>
        <span class="text-xs text-primary font-mono font-semibold">{volume()}%</span>
      </div>

      <Slider value={volume()} min={0} max={100} step={1} onValueChange={setVolume} class="mb-2" />
    </div>
  )
}

Set a numeric range#

Pass an ordered pair for two thumbs. minStepsBetweenThumbs and allowThumbCrossing constrain whether the thumbs may overlap.

import { Checkbox, Slider } from 'moraine'
import { createSignal } from 'solid-js'

export function RangeSlider() {
  const [rangeValue, setRangeValue] = createSignal<number[]>([20, 75])
  const [minStepsBetweenThumbs, setMinStepsBetweenThumbs] = createSignal(0)
  const [allowThumbCrossing, setAllowThumbCrossing] = createSignal(true)

  return (
    <div class="max-w-xl space-y-3">
      <Checkbox
        checked={allowThumbCrossing()}
        onCheckedChange={setAllowThumbCrossing}
        label="Allow dragging across overlapping thumbs"
      />
      <Checkbox
        checked={minStepsBetweenThumbs() > 0}
        onCheckedChange={(isChecked) => setMinStepsBetweenThumbs(isChecked ? 10 : 0)}
        label="Min steps between thumbs"
      />
      <Slider
        value={rangeValue()}
        min={0}
        max={100}
        step={1}
        minStepsBetweenThumbs={minStepsBetweenThumbs()}
        allowThumbCrossing={allowThumbCrossing()}
        onValueChange={(next) => {
          if (Array.isArray(next)) {
            setRangeValue(next)
          }
        }}
      />
      <p class="text-xs text-muted-foreground w-50">
        Range: {rangeValue()[0]} - {rangeValue()[1]}
      </p>
      <p class="text-xs text-muted-foreground w-50">
        Thumb crossing:{' '}
        {allowThumbCrossing() && minStepsBetweenThumbs() === 0 ? 'Enabled' : 'Constrained'}
      </p>
      <p class="text-xs text-muted-foreground w-50">Min steps between: {minStepsBetweenThumbs()}</p>
    </div>
  )
}

Bind brightness to a form#

Place the slider in form.Field so the schema owns the committed number.

import { Button, createForm, Slider } from 'moraine'
import type { SliderT } from 'moraine'
import { createSignal, untrack } from 'solid-js'
import * as v from 'valibot'

export function FormIntegration() {
  const [formState, setFormState] = createSignal({
    volume: 10,
  })

  const updateFormVolume = (nextValue: SliderT.Value) => {
    const next = Array.isArray(nextValue) ? (nextValue[0] ?? 0) : nextValue
    setFormState((prev) => ({ ...prev, volume: next }))
  }
  const form = createForm({
    schema: v.object({ volume: v.pipe(v.number(), v.minValue(20, 'Volume must be at least 20.')) }),
    initialInput: untrack(formState),
    validate: 'input',
  })

  return (
    <form.Form>
      <div class="max-w-xl space-y-4">
        <form.Field name="volume" label="Volume" description="Keep it at least 20.">
          <Slider value={formState().volume} onValueChange={updateFormVolume} />
        </form.Field>
        <div class="flex gap-3 items-center">
          <Button type="submit" variant="soft" tone="neutral" size="sm">
            Validate
          </Button>
          <p class="text-xs text-muted-foreground">Current volume: {formState().volume}</p>
        </div>
      </div>
    </form.Form>
  )
}

Snap volume to ticks#

Set step so drag and keyboard land on increments. Enable markers to draw those ticks on the track.

import { Slider } from 'moraine'
import { createSignal } from 'solid-js'

export function StepMarker() {
  const [value, setValue] = createSignal(40)
  const [range, setRange] = createSignal([20, 60])

  return (
    <div class="max-w-md w-full space-y-6">
      <div class="space-y-2">
        <div class="text-xs text-muted-foreground flex justify-between">
          <span>Stepped single (step = 10)</span>
          <span class="text-foreground font-mono">{value()}</span>
        </div>
        <Slider
          value={value()}
          min={0}
          max={100}
          step={10}
          markers
          onValueChange={(val) => {
            if (typeof val === 'number') {
              setValue(val)
            }
          }}
        />
      </div>

      <div class="space-y-2">
        <div class="text-xs text-muted-foreground flex justify-between">
          <span>Stepped range (step = 20)</span>
          <span class="text-foreground font-mono">
            {range()[0]} - {range()[1]}
          </span>
        </div>
        <Slider
          defaultValue={[20, 60]}
          value={range()}
          min={0}
          max={100}
          step={20}
          markers
          onValueChange={(val) => {
            if (Array.isArray(val)) {
              setRange(val)
            }
          }}
        />
      </div>
    </div>
  )
}

API Reference#

Attributes#

Attributes
data-disabled
Slot: sliderslider-thumb
Description: Present when the component, slot, or item is disabled.
data-dragging
Slot: sliderslider-thumb
Description: Present while the related thumb or handle is being dragged.
data-invalid
Slot: sliderslider-thumb
Description: Present when the field or form has a validation error.
data-multiple
Slot: sliderslider-range
Description: Present when the control contains or selects multiple values.
data-readonly
Slot: sliderslider-thumb
Description: Present when the field is in read-only mode.
data-required
Slot: sliderslider-thumb
Description: Present when the field input is required.
data-reversed
Slot: sliderslider-rangeslider-thumb
Description: Present when the component direction or range is reversed.
data-swipe-ignore
Slot: slider
Description: —
data-empty
Slot: slider-range
Description: —
data-active
Slot: slider-marker
Description: Present when the item or trigger is active.
data-focus-visible
Slot: slider-thumb
Description: —

Props#

Props for the Slider component. Renders a <div> element by default.

Prop