Skip to example

Animate on state change

An example of using Motion's animate function in Svelte. An $effect animates the element whenever its state changes, and a new animation interrupts the current one with the same velocity.

Svelte

Source code

<script>
  import { animate } from "motion"

  let isOpen = $state(false)
  let box

  $effect(() => {
    animate(
      box,
      {
        rotate: isOpen ? 180 : 0,
        borderRadius: isOpen ? "50%" : "10px",
      },
      { type: "spring", visualDuration: 0.4, bounce: 0.3 }
    )
  })
</script>

<div class="example">
  <div class="box" bind:this={box}></div>
  <button class="toggle" onclick={() => (isOpen = !isOpen)}>
    Toggle
  </button>
</div>

<style>
  .example {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 40px;
  }

  .box {
    width: 100px;
    height: 100px;
    background-color: var(--hue-1);
    border-radius: 10px;
  }

  .toggle {
    padding: 10px 20px;
    border: none;
    border-radius: 999px;
    background-color: var(--hue-1-transparent);
    color: var(--hue-1);
    font: inherit;
    cursor: pointer;
  }
</style>