DocumentationMagnetic

Magnetic

Pulls an isolated child toward a fine pointer and settles with a spring.

Svelte

Shared live previews stay running while you switch code examples and API documentation.

Restrained pull

Place content in the default slot.. Native attributes use Vue spelling, and component refs expose element.

Quick start

Add to your project

Copy the component and everything it needs into your Vue 3.5+ project.

RecommendedUse the shadcn-vue CLI
npx shadcn-vue@2.8.2 add https://kida-ui.onrender.com/r/vue/magnetic.json

Run this from a project with components.json. The CLI creates all required files and installs the declared runtime dependencies. New to shadcn? Follow theinstallation guide first.

View registry JSON
Copy manually5 files

1. Install runtime dependencies

npm install motion@^13.1.0

2. Create the source files

Keep this directory structure so the component's relative imports continue to work.

src/components/ui/kida/magnetic.vue
<script setup lang="ts">
import './magnetic.css'
import { magnetic } from './magnetic.motion.js'
import { shallowRef, watch } from 'vue'
import type { MagneticProps } from './magnetic.types.js'

defineOptions({ name: 'KidaMagnetic', inheritAttrs: false })
const props = defineProps<MagneticProps>()
const element = shallowRef<HTMLSpanElement | null>(null)
const target = shallowRef<HTMLSpanElement | null>(null)
defineExpose({ element })

watch(
  [() => element.value, () => target.value, () => props.strength, () => props.maxDistance],
  (_, __, onCleanup) => {
    if (element.value && target.value)
      onCleanup(magnetic(element.value, target.value, { ...props }))
  },
  { flush: 'post' },
)
</script>

<template>
  <span v-bind="$attrs" ref="element" data-kida-magnetic="">
    <span ref="target" :class="props.targetClass" data-kida-magnetic-target=""><slot /></span>
  </span>
</template>
src/components/ui/kida/magnetic.types.ts
import type { MagneticOptions } from './magnetic.motion.js';

export interface MagneticProps extends MagneticOptions {
    /** Class applied to the moving inner span. */
    targetClass?: string;
}

/** Vue component refs expose the root DOM element, null when presence removes it. */
export interface KidaElement {
    element: HTMLElement | null;
}
src/components/ui/kida/magnetic.css
[data-kida-magnetic] {
  --kida-magnetic-activation-distance: 2rem;

  display: inline-flex;
  position: relative;
  isolation: isolate;
}

/* Keep hover detection around the stationary root. Without this stable area, translating
   the target can move it out from under the pointer and immediately cancel the effect. */
[data-kida-magnetic]::before {
  position: absolute;
  z-index: -1;
  inset: calc(-1 * var(--kida-magnetic-activation-distance));
  content: "";
}

[data-kida-magnetic-target] {
  display: inline-flex;
}

@media (prefers-reduced-motion: reduce) {
  [data-kida-magnetic-target] {
    /* biome-ignore lint/complexity/noImportantStyles: stops an in-flight inline transform */
    transform: none !important;
  }
}
src/components/ui/kida/magnetic.motion.ts
import { motionValue, springValue, styleEffect } from 'motion'
import { prefersReducedMotion } from './reduced-motion.motion.js'

export interface MagneticOptions {
  /** Portion of pointer distance followed by the target. @default 0.22 */
  strength?: number
  /** Maximum travel in CSS pixels. @default 18 */
  maxDistance?: number
}

const DEFAULTS = { strength: 0.22, maxDistance: 18 } as const

export function magnetic(
  root: HTMLElement,
  target: HTMLElement,
  options: MagneticOptions = {},
): () => void {
  if (prefersReducedMotion()) return () => {}

  const { strength = DEFAULTS.strength, maxDistance = DEFAULTS.maxDistance } = options
  let bounds = root.getBoundingClientRect()
  let frame = 0
  let x = 0
  let y = 0
  let inside = false

  // Retarget one persistent spring instead of canceling and recreating a DOM animation
  // for every pointer frame. Recreating it continually throws away most of the spring's
  // velocity, which makes a moving pointer look as though it barely affects the target.
  const sourceX = motionValue(0)
  const sourceY = motionValue(0)
  const spring = { stiffness: 360, damping: 24, mass: 0.65 }
  const springX = springValue(sourceX, spring)
  const springY = springValue(sourceY, spring)
  const stopStyleEffect = styleEffect(target, { x: springX, y: springY })

  let xSettled = true
  let ySettled = true
  const settle = () => {
    if (inside || !xSettled || !ySettled || sourceX.get() !== 0 || sourceY.get() !== 0) return
    target.style.transform = 'none'
    target.style.willChange = 'auto'
  }
  const stopXStart = springX.on('animationStart', () => {
    xSettled = false
  })
  const stopYStart = springY.on('animationStart', () => {
    ySettled = false
  })
  const stopXComplete = springX.on('animationComplete', () => {
    xSettled = true
    settle()
  })
  const stopYComplete = springY.on('animationComplete', () => {
    ySettled = true
    settle()
  })

  const move = () => {
    frame = 0
    sourceX.set(x)
    sourceY.set(y)
  }

  const onEnter = () => {
    inside = true
    bounds = root.getBoundingClientRect()
    target.style.willChange = 'transform'
  }
  const onMove = (event: PointerEvent) => {
    if (event.pointerType === 'touch') return
    const centerX = bounds.left + bounds.width / 2
    const centerY = bounds.top + bounds.height / 2
    x = Math.max(-maxDistance, Math.min(maxDistance, (event.clientX - centerX) * strength))
    y = Math.max(-maxDistance, Math.min(maxDistance, (event.clientY - centerY) * strength))
    if (!frame) frame = requestAnimationFrame(move)
  }
  const onLeave = () => {
    inside = false
    if (frame) cancelAnimationFrame(frame)
    frame = 0
    x = 0
    y = 0
    sourceX.set(0)
    sourceY.set(0)
    settle()
  }

  root.addEventListener('pointerenter', onEnter)
  root.addEventListener('pointermove', onMove)
  root.addEventListener('pointerleave', onLeave)
  const observer = new ResizeObserver(() => {
    bounds = root.getBoundingClientRect()
  })
  observer.observe(root)

  return () => {
    root.removeEventListener('pointerenter', onEnter)
    root.removeEventListener('pointermove', onMove)
    root.removeEventListener('pointerleave', onLeave)
    observer.disconnect()
    if (frame) cancelAnimationFrame(frame)
    stopXStart()
    stopYStart()
    stopXComplete()
    stopYComplete()
    stopStyleEffect()
    springX.destroy()
    springY.destroy()
    sourceX.destroy()
    sourceY.destroy()
    target.style.transform = 'none'
    target.style.willChange = 'auto'
  }
}
src/components/ui/kida/reduced-motion.motion.ts
const QUERY = '(prefers-reduced-motion: reduce)'

/**
 * Whether the user has asked for reduced motion.
 *
 * SSR-safe: returns `false` when there is no `window`, matching the CSS default
 * (the `prefers-reduced-motion` media query in `@kida-ui/styles` is the real guard;
 * this is for the JS-driven paths that CSS cannot express).
 */
export function prefersReducedMotion(): boolean {
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false
  return window.matchMedia(QUERY).matches
}

/**
 * Subscribe to changes of the reduced-motion preference.
 * Returns an unsubscribe function. No-op (and immediately unsubscribable) on the server.
 */
export function watchReducedMotion(onChange: (reduced: boolean) => void): () => void {
  if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return () => {}

  const list = window.matchMedia(QUERY)
  const handler = (event: MediaQueryListEvent) => onChange(event.matches)
  list.addEventListener('change', handler)
  return () => list.removeEventListener('change', handler)
}
<script setup lang="ts">
import Magnetic from '@/components/ui/kida/magnetic.vue'
</script>

<template>
  <Magnetic><button type="button">Come closer</button></Magnetic>
</template>

API

Props

Prop Type Default Description
strength number 0.22 Portion of pointer distance followed.
maxDistance number 18 Maximum travel in CSS pixels.
targetClass string — Class applied to the isolated moving layer.

The root also accepts span attributes, class, style, event handlers, and a component ref exposing element.

CSS custom properties

Property Default Description
--kida-magnetic-activation-distance 2rem Stable pointer area around the stationary root.

Customization

Use strength to tune how closely the child follows the pointer and maxDistance to cap its travel. --kida-magnetic-activation-distance controls the stationary hover area; keep it large enough that the moving child cannot escape the pointer too easily.

Accessibility and input behavior

Only mouse and pen movement activate the effect. Touch input is ignored, and the wrapped control continues to own its click, focus, and keyboard behavior. Magnetic does not reveal information, so no keyboard-only motion is required.

When reduced motion is requested, pointer tracking is disabled and the child stays in its natural position. The stationary root keeps the hit area predictable while the visible child moves.

Troubleshooting

Magnetic intentionally ignores touch input and does not move under reduced motion. Test with a mouse or pen, and avoid applying another transform directly to the generated target layer.