Skip to example

Reorder items

An example of animating list reordering using Motion's animateLayout. Items smoothly animate to their new positions when shuffled.

JavaScript

Source code

<ul class="container">
    <li data-layout style="background-color: var(--hue-1)"></li>
    <li data-layout style="background-color: var(--hue-2)"></li>
    <li data-layout style="background-color: var(--hue-3)"></li>
    <li data-layout style="background-color: var(--hue-4)"></li>
</ul>

<script type="module">
    import { animateLayout } from "motion"

    const container = document.querySelector(".container")
    const items = Array.from(container.querySelectorAll("li"))

    function shuffle() {
        const shuffled = [...items].sort(() => Math.random() - 0.5)

        animateLayout(
            () => shuffled.forEach((item) => container.appendChild(item)),
            {
                duration: 0.6,
                ease: [0.4, 0, 0.2, 1],
            }
        )
    }

    // Shuffle every second
    setInterval(shuffle, 1000)
</script>

<style>
    .container {
        list-style: none;
        padding: 0;
        margin: 0;
        position: relative;
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        width: 210px;
        flex-direction: row;
        justify-content: center;
        align-items: center;
    }

    .container li {
        width: 100px;
        height: 100px;
        border-radius: 10px;
    }
</style>