Skip to example

AnimateView: Toggle

An iOS-style toggle whose knob glides between states with a spring, powered by AnimateView update animations.

Vue

Source code

<script setup lang="ts">
import { AnimateView, spring, startTransition } from 'motion-v'
import { ref } from 'vue'

const isOn = ref(false)

const springTransition = {
  type: spring,
  visualDuration: 0.2,
  bounce: 0.2,
}

function toggle() {
  startTransition(() => {
    isOn.value = !isOn.value
  })
}
</script>

<template>
  <div class="toggle-example">
    <AnimateView :transition="springTransition">
      <button
        class="toggle-track"
        :class="{ on: isOn }"
        @click="toggle"
      >
        <AnimateView :transition="springTransition">
          <div class="toggle-handle" />
        </AnimateView>
      </button>
    </AnimateView>
  </div>
</template>

<style scoped>
.toggle-example {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.toggle-track {
  width: 100px;
  height: 50px;
  border-radius: 50px;
  cursor: pointer;
  display: flex;
  justify-content: flex-start;
  padding: 10px;
  border: none;
  background-color: rgba(255, 255, 255, 0.15);
}

.toggle-track.on {
  justify-content: flex-end;
  background-color: var(--hue-6);
}

.toggle-handle {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: white;
}
</style>