DocumentationMagnetic

Magnetic

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

Restrained pull

Place content inside the component. Native attributes and events use Svelte spelling, such as onclick, and bind:element gives you the root DOM element.

Quick start

Add to your project

Copy the component and everything it needs into your Svelte 5 project.

RecommendedUse the shadcn-svelte CLI
npx shadcn-svelte@1.8.0 add https://kida-ui.onrender.com/r/svelte/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.

Files land in src/lib/components/ui/kida by default. SvelteKit 3 projects import them through #lib; SvelteKit 2 and Vite projects use $lib, as in the examples here.

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/lib/components/ui/kida/magnetic.svelte
<script lang="ts">
import './magnetic.css'
import { magnetic } from './magnetic.motion.js'
import { untrack } from 'svelte'
import type { MagneticProps } from './magnetic.types.js'

let {
  strength,
  maxDistance,
  targetClass,
  element = $bindable(null),
  children,
  ...rest
}: MagneticProps = $props()

let target = $state<HTMLSpanElement | null>(null)

// A parent's {...spread} invalidates every prop when any one changes. These deriveds only
// notify on a real value change, so unrelated updates cannot restart the controller.
const root = $derived(element)
const optionsKey = $derived(`${strength}:${maxDistance}`)

$effect(() => {
  const outer = root
  const inner = target
  void optionsKey
  if (!outer || !inner) return
  return untrack(() => magnetic(outer, inner, { strength, maxDistance }))
})
</script>

<span {...rest} bind:this={element} data-kida-magnetic=""><span bind:this={target} class={targetClass} data-kida-magnetic-target="">{@render children?.()}</span></span>
src/lib/components/ui/kida/magnetic.types.ts
import type { MagneticOptions } from './magnetic.motion.js';

import type { HTMLAttributes } from 'svelte/elements';

export interface MagneticProps extends MagneticOptions, HTMLAttributes<HTMLSpanElement> {
    /** Class applied to the moving inner span. */
    targetClass?: string;
    /** Bind to read the root DOM element; null after unmount. */
    element?: HTMLSpanElement | null;
}
src/lib/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/lib/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/lib/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 lang="ts">
import Magnetic from '$lib/components/ui/kida/magnetic.svelte'
</script>

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

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.
element HTMLSpanElement | null null Use bind:element to read the root DOM element.

The root also accepts span attributes, class, style, and event handlers.

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.