Skip to content
Brok UI

Loading…

No results

Compare Slider

Open source

Before/after image (or arbitrary content) comparison with a keyboard-accessible, RTL-aware draggable divider.

Version
v1.2.2
Stability
stable
License
MIT
Related
Image Picker
Blur Vignette
Editor Media

Preview

Final
Draft
Orientation
previews.components.compare-slider.default.blade.php Blade
{{-- Two layers at full size, the first clipped to the divider, so they stay
     aligned while you drag. Any content works; here two gradients stand in
     for photographs so the preview needs no network. --}}
<x-ui.compare-slider before-label="Before" after-label="After" class="aspect-video w-full max-w-xl border border-border">
    <x-slot:before>
        <div class="flex size-full items-center justify-center bg-gradient-to-br from-muted to-secondary">
            <span class="text-5xl font-semibold tracking-tight text-muted-foreground">Draft</span>
        </div>
    </x-slot:before>
    <x-slot:after>
        <div class="flex size-full items-center justify-center bg-gradient-to-br from-primary/80 to-primary">
            <span class="text-5xl font-semibold tracking-tight text-primary-foreground">Final</span>
        </div>
    </x-slot:after>
</x-ui.compare-slider>
Horizontal Current
Vertical Current

Installation

terminal
php artisan ui:add compare-slider

Note

This component ships an Alpine behavior module at resources/js/ui/compare-slider.js. Import it once from your bundle so it registers on alpine:init:

resources/js/ui/index.js JS
import './compare-slider.js';

Registry contract

php artisan ui:add compare-slider writes only the files below. The CLI validates each file hash before writing and asks before it replaces a local change, unless you pass --force.

  • blade resources/views/components/ui/compare-slider.blade.php
  • js resources/js/ui/compare-slider.js
Registry dependencies
None — installs on its own.
Packages
composer: jml/brok:^0.2
npm: alpinejs

Use with AI

A brief for your coding agent: install command, usage, props, guidance and the rules. Copy it, or open a prompt about this component in an assistant.

compare-slider.md
# Brok UI: Compare Slider (`compare-slider`)

Before/after image (or arbitrary content) comparison with a keyboard-accessible, RTL-aware draggable divider.

Brok UI is a Laravel Blade component registry. Installed components are plain Blade files the app owns.

## Install

```bash
php artisan ui:add compare-slider
```

## Usage

```blade
{{-- Two layers at full size, the first clipped to the divider, so they stay
     aligned while you drag. Any content works; here two gradients stand in
     for photographs so the preview needs no network. --}}
<x-ui.compare-slider before-label="Before" after-label="After" class="aspect-video w-full max-w-xl border border-border">
    <x-slot:before>
        <div class="flex size-full items-center justify-center bg-gradient-to-br from-muted to-secondary">
            <span class="text-5xl font-semibold tracking-tight text-muted-foreground">Draft</span>
        </div>
    </x-slot:before>
    <x-slot:after>
        <div class="flex size-full items-center justify-center bg-gradient-to-br from-primary/80 to-primary">
            <span class="text-5xl font-semibold tracking-tight text-primary-foreground">Final</span>
        </div>
    </x-slot:after>
</x-ui.compare-slider>
```

## Props

- `before` (mixed|null, default `null`) — Before-state content, typically an image URL or slot content.
- `after` (mixed|null, default `null`) — After-state content, typically an image URL or slot content.
- `value` (int, default `50`) — Initial divider position as a percent (0-100).
- `orientation` (string, default `horizontal`) — Divider axis: horizontal (drags left/right) or vertical (drags up/down).
- `name` (mixed|null, default `null`) — When set, mirrors the divider position into a hidden input for form submission.
- `beforeLabel` (mixed|null, default `null`) — Caption shown over the before side.
- `afterLabel` (mixed|null, default `null`) — Caption shown over the after side.

## Use when

- Use when continuous adjustment or immediate visual feedback helps users choose a value.
- Showing a before/after comparison, such as an image edit, redesign, or restoration, with a draggable reveal divider.
- Comparing two arbitrary pieces of content side by side with a slider, not just two images.

## Avoid when

- Do not use for precise values or broad ranges without good landmarks; direct entry is better when accuracy matters.
- The two states should be visible at once, side by side, rather than revealed by dragging; use a plain two-column layout.
- Comparing more than two states; a slider only supports a single before/after split.

## Anti-patterns

- Using sliders for precise or unbounded values

## Rules

- Use the `<brok:compare-slider>` tag (or `<x-ui.compare-slider>`) in Blade; do not rewrite the component.
- Prefer the documented props and variants over utility-class overrides; when a utility must win, use the `!` important modifier.
- Use semantic design tokens (`bg-primary`, `text-muted-foreground`), never raw colour utilities.
- Keep the `data-slot` attributes; they are the styling and test hooks.

## Links

- Docs: https://brokui.dev/docs/components/compare-slider
- Registry JSON (files, props, contract): https://brokui.dev/r/open/compare-slider.json

Working in Claude Code, Cursor or Codex? Give the agent the whole registry through the MCP server or the Brok UI skill.

API

manifest knowledge + registry-derived coverage

Props

Props accepted by this component: name, type, default value and description.
Prop Type Default Description
before mixed | null null Before-state content, typically an image URL or slot content.
after mixed | null null After-state content, typically an image URL or slot content.
value int 50 Initial divider position as a percent (0-100).
orientation string horizontal Divider axis: horizontal (drags left/right) or vertical (drags up/down).
name mixed | null null When set, mirrors the divider position into a hidden input for form submission.
beforeLabel mixed | null null Caption shown over the before side.
afterLabel mixed | null null Caption shown over the after side.

Slots

  • default —

Data slots

Stable hooks for CSS overrides and browser tests.

compare-slider compare-slider-after compare-slider-after-label compare-slider-before compare-slider-before-label compare-slider-divider compare-slider-handle

Behavior

  • Dragging the handle moves the divider and reveals more of the after content on one side and the before content on the other.
  • The handle also responds to arrow keys, stepping the divider position, with RTL-aware direction for horizontal orientation.
  • Installs a JavaScript behavior module when the registry item includes resources/js/ui files.
  • Declares registry capability flags: a11y, interactive, responsive, rtl, darkMode.

Guidance

Continuous value control

Adjust an intuitive continuous value.

Use when

  • Use when continuous adjustment or immediate visual feedback helps users choose a value.
  • Showing a before/after comparison, such as an image edit, redesign, or restoration, with a draggable reveal divider.
  • Comparing two arbitrary pieces of content side by side with a slider, not just two images.

Avoid when

  • Do not use for precise values or broad ranges without good landmarks; direct entry is better when accuracy matters.
  • The two states should be visible at once, side by side, rather than revealed by dragging; use a plain two-column layout.
  • Comparing more than two states; a slider only supports a single before/after split.

Use instead

  • Number field for precise entry
  • Select for discrete values

Anti-patterns

  • Using sliders for precise or unbounded values
Anatomy
root compare-slider-after compare-slider-before compare-slider-before-label compare-slider-after-label compare-slider-divider compare-slider-handle
Theming hooks
compare-slider compare-slider-after compare-slider-after-label compare-slider-before compare-slider-before-label compare-slider-divider compare-slider-handle

Accessibility

WCAG 2.2 AA Keyboard focus-visible RTL-ready Localized labels Dark mode
Keyboard
ArrowUp ArrowDown ArrowLeft ArrowRight Home End PageUp PageDown
Focus
managed
  • The handle is a real, keyboard-focusable control that responds to arrow keys as a slider, so the comparison is operable without a pointer.
  • Before and after labels are exposed as visible captions rather than color alone distinguishing the two sides.
  • Semantic HTML and a stable data-slot attribute for styling and scripting hooks.
  • Focus-visible rings use the ring token, so keyboard focus is always visible.
  • Disabled and invalid states are conveyed to assistive tech, not by color alone.
  • Targets WCAG 2.2 AA; verify contrast in light, dark, admin and customer surfaces in the preview.
  • Labels go through __() and layout uses logical properties (ms-*, text-start), so it mirrors under dir="rtl" — flip the preview to RTL to confirm.
  • Dark mode uses the same semantic tokens under the dark class; high contrast follows forced-color system tokens.

Livewire

Needs wire:key

Add a stable wire:key when Livewire can reorder this interactive component.

livewire-component.blade.php Blade
<div wire:key="compare-slider-{{ $record->id }}">
    {{-- Two layers at full size, the first clipped to the divider, so they stay
         aligned while you drag. Any content works; here two gradients stand in
         for photographs so the preview needs no network. --}}
    <x-ui.compare-slider before-label="Before" after-label="After" class="aspect-video w-full max-w-xl border border-border">
        <x-slot:before>
            <div class="flex size-full items-center justify-center bg-gradient-to-br from-muted to-secondary">
                <span class="text-5xl font-semibold tracking-tight text-muted-foreground">Draft</span>
            </div>
        </x-slot:before>
        <x-slot:after>
            <div class="flex size-full items-center justify-center bg-gradient-to-br from-primary/80 to-primary">
                <span class="text-5xl font-semibold tracking-tight text-primary-foreground">Final</span>
            </div>
        </x-slot:after>
    </x-ui.compare-slider>
</div>

Validation

Validation support: native. Keep the error message connected with aria-describedby.

livewire-form.blade.php Blade
<form wire:submit="save" class="space-y-2">
    <brok:compare-slider
        wire:model="value"
        :aria-invalid="$errors->has('value') ? 'true' : 'false'"
        aria-describedby="value-error"
    />

    @error('value')
        <p id="value-error" role="alert">{{ $message }}</p>
    @enderror

    <brok:button type="submit" wire:loading.attr="disabled">
        <span wire:loading.remove>Save</span>
        <span wire:loading>Saving…</span>
    </brok:button>
</form>

Source

The exact, editable files ui:add writes into your app. Previews render this same code; there are no preview-only components.

resources/views/components/ui/compare-slider.blade.php Blade
@props([
    'before'      => null,
    'after'       => null,
    'value'       => 50,
    'orientation' => 'horizontal',
    'name'        => null,
    // Optional corner labels ("Before" / "After"); omit both for none.
    'beforeLabel' => null,
    'afterLabel'  => null,
])

{{--
    Compare Slider — before/after image (or arbitrary content) comparison with a
    draggable divider. Both layers fill the container at full size; the "before"
    layer is clipped with `clip-path` to `value`%, so the two images stay
    pixel-aligned while the divider moves (shrinking the layer's width would
    re-crop the picture instead).

    Slots `before` / `after` take priority over the `$before` / `$after` image
    URL props so callers can compare any content, not just images.

    Keyboard: ArrowLeft/Right (horizontal) or Up/Down (vertical) ±1; PageUp/Down
    ±10; Home/End to snap ends. RTL-aware in horizontal mode.
--}}
<div
    x-data="uiCompareSlider({ value: @js((float) $value), orientation: @js($orientation) })"
    x-ref="root"
    data-slot="compare-slider"
    @pointerdown="startDrag($event)"
    {{ $attributes->merge(['class' => 'relative overflow-hidden rounded-lg select-none cursor-col-resize']) }}
>
    {{-- After layer (base, fills container) --}}
    <div
        data-slot="compare-slider-after"
        class="w-full h-full"
    >
        @if ($after instanceof \Illuminate\View\ComponentSlot)
            {{ $after }}
        @elseif ($after !== null)
            <img
                src="{{ $after }}"
                alt=""
                class="pointer-events-none select-none object-cover w-full h-full"
                draggable="false"
            />
        @endif
    </div>

    {{-- Before layer: full size, clipped to value% so it stays aligned with the after layer --}}
    <div
        data-slot="compare-slider-before"
        class="absolute inset-0 transition-[clip-path] motion-reduce:transition-none"
        :style="'clip-path:' + clipPath() + (dragging ? '; transition: none' : '')"
    >
        @if ($before instanceof \Illuminate\View\ComponentSlot)
            {{ $before }}
        @elseif ($before !== null)
            <img
                src="{{ $before }}"
                alt=""
                class="pointer-events-none select-none object-cover w-full h-full"
                draggable="false"
            />
        @endif
    </div>

    @if (filled($beforeLabel) || filled($afterLabel))
        <div class="pointer-events-none absolute inset-0" aria-hidden="true">
            @if (filled($beforeLabel))
                <span data-slot="compare-slider-before-label" class="absolute start-2 top-2 rounded-sm bg-background/85 px-2 py-0.5 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm">{{ $beforeLabel }}</span>
            @endif
            @if (filled($afterLabel))
                <span data-slot="compare-slider-after-label" class="absolute end-2 top-2 rounded-sm bg-background/85 px-2 py-0.5 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm">{{ $afterLabel }}</span>
            @endif
        </div>
    @endif

    {{-- Divider line --}}
    <div
        data-slot="compare-slider-divider"
        class="absolute bg-background shadow-md transition-[inset] motion-reduce:transition-none"
        :class="orientation === 'vertical'
            ? 'left-0 right-0 h-0.5 -translate-y-1/2'
            : 'top-0 bottom-0 w-0.5 -translate-x-1/2'"
        :style="(orientation === 'vertical'
            ? 'inset-block-start:' + value + '%; inset-inline-start:0'
            : 'inset-inline-start:' + value + '%; inset-block-start:0') + (dragging ? '; transition: none' : '')"
    >
        {{-- Handle / thumb --}}
        <button
            type="button"
            data-slot="compare-slider-handle"
            role="slider"
            tabindex="0"
            aria-valuemin="0"
            aria-valuemax="100"
            :aria-valuenow="Math.round(value)"
            :aria-orientation="orientation"
            aria-label="{{ __('Compare slider') }}"
            @keydown="onKey($event)"
            class="absolute flex size-8 max-w-none items-center justify-center rounded-full bg-background border border-border shadow-md -translate-x-1/2 -translate-y-1/2 cursor-grab active:cursor-grabbing focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring transition-shadow motion-reduce:transition-none"
            :style="orientation === 'vertical'
                ? 'inset-inline-start:50%; inset-block-start:50%'
                : 'inset-inline-start:50%; inset-block-start:50%'"
        >
            {{-- Grip icon --}}
            <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                class="size-4 text-muted-foreground"
                aria-hidden="true"
            >
                @if ($orientation === 'vertical')
                    {{-- Up/down chevrons for vertical --}}
                    <polyline points="18 8 12 2 6 8" />
                    <polyline points="6 16 12 22 18 16" />
                @else
                    {{-- Left/right chevrons for horizontal --}}
                    <polyline points="8 18 2 12 8 6" />
                    <polyline points="16 6 22 12 16 18" />
                @endif
            </svg>
        </button>
    </div>

    @if ($name)
        <input type="hidden" name="{{ $name }}" :value="value" />
    @endif
</div>
resources/js/ui/compare-slider.js JS
/**
 * Compare Slider behavior (spec §19 behavior layer).
 *
 * Holds a single `value` (0–100) representing how much of the "before" layer
 * is revealed. The divider is positioned with the logical `inset-inline-start`
 * (horizontal) or `inset-block-start` (vertical), so the component mirrors
 * automatically under `dir="rtl"`. Pointer and keyboard input account for
 * direction so dragging and arrow keys always feel correct.
 *
 * Self-registers on `alpine:init` so import order does not matter — import
 * this file once from your bundle (e.g. resources/js/ui/index.js).
 */
document.addEventListener('alpine:init', () => {
    window.Alpine.data('uiCompareSlider', (config = {}) => ({
        value: config.value ?? 50,
        orientation: config.orientation ?? 'horizontal',

        /** True while a pointer drag owns the divider (kills transitions inline). */
        dragging: false,

        /** The before layer shows its first value% — from the start edge, or the top when vertical. */
        clipPath() {
            const hidden = 100 - this.value;
            if (this.orientation === 'vertical') return `inset(0 0 ${hidden}% 0)`;
            const rtl = this.$refs.root && getComputedStyle(this.$refs.root).direction === 'rtl';
            return rtl ? `inset(0 0 0 ${hidden}%)` : `inset(0 ${hidden}% 0 0)`;
        },

        // Bound listener refs so we can remove exactly what we added.
        _move: null,
        _up: null,

        destroy() {
            // Remove any listeners still attached if unmounted mid-drag.
            window.removeEventListener('pointermove', this._move);
            window.removeEventListener('pointerup', this._up);
        },

        /**
         * Compute the percentage from a pointer position relative to the root
         * element's bounding box, taking RTL into account for horizontal mode.
         */
        setFromClientPos(clientX, clientY) {
            const r = this.$refs.root.getBoundingClientRect();
            let ratio;

            if (this.orientation === 'vertical') {
                ratio = (clientY - r.top) / r.height;
            } else {
                ratio = (clientX - r.left) / r.width;
                if (getComputedStyle(this.$refs.root).direction === 'rtl') {
                    ratio = 1 - ratio;
                }
            }

            this.value = Math.min(100, Math.max(0, ratio * 100));
        },

        startDrag(e) {
            this.dragging = true;
            this.setFromClientPos(e.clientX, e.clientY);
            // Bind once so the same refs can be removed later (here or in destroy()).
            this._move = (ev) => this.setFromClientPos(ev.clientX, ev.clientY);
            this._up = () => {
                this.dragging = false;
                window.removeEventListener('pointermove', this._move);
                window.removeEventListener('pointerup', this._up);
            };
            window.addEventListener('pointermove', this._move);
            window.addEventListener('pointerup', this._up);
        },

        onKey(e) {
            const rtl =
                this.orientation === 'horizontal' &&
                getComputedStyle(this.$refs.root).direction === 'rtl';
            const step = 1;
            const bigStep = 10;

            const dec = (s) => (this.value = Math.max(0, this.value - s));
            const inc = (s) => (this.value = Math.min(100, this.value + s));

            switch (e.key) {
                case 'ArrowLeft':
                    e.preventDefault();
                    rtl ? inc(step) : dec(step);
                    break;
                case 'ArrowRight':
                    e.preventDefault();
                    rtl ? dec(step) : inc(step);
                    break;
                case 'ArrowUp':
                    e.preventDefault();
                    this.orientation === 'vertical' ? dec(step) : inc(step);
                    break;
                case 'ArrowDown':
                    e.preventDefault();
                    this.orientation === 'vertical' ? inc(step) : dec(step);
                    break;
                case 'PageUp':
                    e.preventDefault();
                    inc(bigStep);
                    break;
                case 'PageDown':
                    e.preventDefault();
                    dec(bigStep);
                    break;
                case 'Home':
                    e.preventDefault();
                    this.value = 0;
                    break;
                case 'End':
                    e.preventDefault();
                    this.value = 100;
                    break;
            }
        },
    }));
});

Ownership & lifecycle

Owner, release state, review evidence and adoption for this item.
Owner
Platform UI (@JoshJML)
Current version
1.2.2
Status
Stable
License
open
Accessibility reviewed
No review date recorded
Last breaking change
No date recorded
Deprecation
Not deprecated
Contract
v6
Foundation
≥ 1.0.0