Attachments

Number shuffle

Roll digits as a numeric value changes.

Usage

Import numberShuffle from @mielui/svelte/attachments/number-shuffle and add {@attach numberShuffle({ value })} to a text-only element. Render the final value as its text so it is available before JavaScript loads. Use tabular numerals and reserve enough width for the expected values.

<script lang="ts">
    import { numberShuffle } from '@mielui/svelte/attachments/number-shuffle';
    import { Button } from '@mielui/svelte/components/button';

    let value = $state(72);
    const values = [72, 98, 104, 36];
    function updateValue() {
        value = values[(values.indexOf(value) + 1) % values.length];
    }
</script>

<div class="flex flex-col items-center gap-6">
    <span
        {@attach numberShuffle({ value })}
        class="inline-block min-w-[3ch] text-center text-4xl tabular-nums"
    >
        {value}
    </span>
    <Button variant="secondary" onclick={updateValue}>Update value</Button>
</div>

Formatted values

Pass format to display decimals, separators, or units. Use the same formatter for the element's text. Keep icons and other markup outside the animated element.

Motion and accessibility

Entry starts at zero. Each new value rolls from the number the element showed last, including partway through a roll. The visual digits are hidden from assistive technology, which reads the final text. Reduced motion and disabled theme motion show the final value immediately. Removing the element cleans up the animation.

API reference

numberShuffle takes a NumberShuffleOptions object and returns a Svelte attachment for a text-only HTMLElement. A new options object re-attaches it, which keeps rolling from the value it showed last.

  • value Required
    number

    The target value to display.

  • format
    ((value: number) => string)

    Formats each intermediate and final value.

    Default String

  • duration
    number

    Milliseconds. Defaults to twice the theme panel duration, with a 480ms fallback. Set zero to update immediately.