Skip to example

Layout animation

An example of animating a simple layout change using Motion's animateLayout function.

JavaScript

Source code

<button class="toggle-container">
    <div class="toggle-handle" data-layout></div>
</button>

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

    let isOn = false

    press(".toggle-container", (element) => {
        isOn = !isOn

        animateLayout(
            ".toggle-container",
            () => {
                if (isOn) {
                    element.classList.add("on")
                } else {
                    element.classList.remove("on")
                }
            },
            {
                type: "spring",
                visualDuration: 0.2,
                bounce: 0.2,
            }
        )
    })
</script>

<style>
    .toggle-container {
        width: 100px;
        height: 50px;
        background-color: var(--hue-5-transparent);
        border-radius: 50px;
        cursor: pointer;
        display: flex;
        padding: 10px;
        border: none;
        justify-content: flex-start;
    }

    .toggle-container.on {
        justify-content: flex-end;
    }

    .toggle-handle {
        width: 50px;
        height: 50px;
        background-color: var(--hue-5);
        border-radius: 50%;
    }
</style>