Drag
Any motion component can be made draggable with the drag prop. The component gets full physics-based momentum, elastic constraints, and gesture callbacks.
<motion.div drag /><motion.div drag />// drag the box around
Usage
Set drag to true to enable dragging on both axes:
<motion.div drag /><motion.div drag />To restrict dragging to a single axis, pass "x" or "y":
<motion.div drag="x" /><motion.div drag="x" />Constraints
Drag movement can be constrained with the dragConstraints prop. Constraints can be defined as pixel offsets from the element’s origin, or as a reference to another element.
Pixel constraints
Pass an object with top, left, right, and bottom values (in pixels):
<motion.div
drag
dragConstraints={{ left: -100, right: 100, top: -50, bottom: 50 }}
/><motion.div
drag
dragConstraints={{ left: -100, right: 100, top: -50, bottom: 50 }}
/>Element constraints
Pass an element reference to constrain dragging within that element’s bounding box:
<script lang="ts">
import { motion } from '@humanspeak/svelte-motion'
let bounds: HTMLElement | null = null
</script>
<div bind:this={bounds}>
<motion.div drag dragConstraints={bounds} />
</div><script lang="ts">
import { motion } from '@humanspeak/svelte-motion'
let bounds: HTMLElement | null = null
</script>
<div bind:this={bounds}>
<motion.div drag dragConstraints={bounds} />
</div>// constrained to the dashed area
Function constraints
dragConstraints can also be a function. This is an advanced hook: instead of bounding the drag, the function takes over moving the element. It’s called when each drag starts and receives:
visualElement: the element’s visual element.originPoint: thex/ythe drag started from.elastic: the resolved per-axis, per-side elastic.getAxisMotionValue(axis): thexorymotion value the drag writes to.getProps(): the drag’s options, e.g.dragfor the axes it moves (Motion 14.10).
It returns a point. As the pointer moves, drag writes the pointer’s position into the point’s x/y and calls move(), which decides where the element goes. On release it calls release(velocity, transition) and waits for the promise it returns.
<script lang="ts">
import { motion, type DragConstraintsFunction, type DragPointConstraint } from '@humanspeak/svelte-motion'
const followPointer: DragConstraintsFunction = (ctx) => {
const axes = ctx.getProps().drag // 'x' here
const x = ctx.getAxisMotionValue('x')
const point: DragPointConstraint = {
...ctx.originPoint,
move() {
x.set(point.x)
},
release() {
return Promise.resolve()
}
}
return point
}
</script>
<motion.div drag="x" dragConstraints={followPointer} /><script lang="ts">
import { motion, type DragConstraintsFunction, type DragPointConstraint } from '@humanspeak/svelte-motion'
const followPointer: DragConstraintsFunction = (ctx) => {
const axes = ctx.getProps().drag // 'x' here
const x = ctx.getAxisMotionValue('x')
const point: DragPointConstraint = {
...ctx.originPoint,
move() {
x.set(point.x)
},
release() {
return Promise.resolve()
}
}
return point
}
</script>
<motion.div drag="x" dragConstraints={followPointer} />Elastic
By default, dragging beyond constraints has an elastic feel. Control this with dragElastic:
<!-- No elasticity — hard stop at constraints -->
<motion.div drag dragConstraints={{ left: -100, right: 100 }} dragElastic={0} />
<!-- Full elasticity (default ~0.35) -->
<motion.div drag dragConstraints={{ left: -100, right: 100 }} dragElastic={1} /><!-- No elasticity — hard stop at constraints -->
<motion.div drag dragConstraints={{ left: -100, right: 100 }} dragElastic={0} />
<!-- Full elasticity (default ~0.35) -->
<motion.div drag dragConstraints={{ left: -100, right: 100 }} dragElastic={1} />Set dragElastic to 0 for a hard boundary, or 1 for maximum stretch. Values between 0 and 1 control the amount of elastic overdrag.
Momentum
After releasing a drag, the element continues with momentum by default. Disable this with dragMomentum:
<motion.div drag dragMomentum={false} /><motion.div drag dragMomentum={false} />Fine-tune the physics with dragTransition:
<motion.div
drag
dragTransition={{
bounceStiffness: 300,
bounceDamping: 20,
power: 0.8,
timeConstant: 200
}}
/><motion.div
drag
dragTransition={{
bounceStiffness: 300,
bounceDamping: 20,
power: 0.8,
timeConstant: 200
}}
/>Snap to origin
Set dragSnapToOrigin to spring the element back to its starting position on release:
<motion.div
drag
dragSnapToOrigin
whileDrag={{ scale: 1.05, cursor: 'grabbing' }}
/><motion.div
drag
dragSnapToOrigin
whileDrag={{ scale: 1.05, cursor: 'grabbing' }}
/>Direction lock
When dragDirectionLock is enabled and both axes are allowed, the drag locks to whichever axis the user moves first (threshold: 4px):
<script lang="ts">
import { motion } from '@humanspeak/svelte-motion'
let lockedAxis = $state<'x' | 'y' | null>(null)
</script>
<motion.div
drag
dragDirectionLock
onDirectionLock={(axis) => (lockedAxis = axis)}
/><script lang="ts">
import { motion } from '@humanspeak/svelte-motion'
let lockedAxis = $state<'x' | 'y' | null>(null)
</script>
<motion.div
drag
dragDirectionLock
onDirectionLock={(axis) => (lockedAxis = axis)}
/>Drag controls
Use createDragControls to start a drag from an external element, like a drag handle:
<script lang="ts">
import { motion, createDragControls } from '@humanspeak/svelte-motion'
const controls = createDragControls()
</script>
<button onpointerdown={(e) => controls.start(e)}>Drag handle</button>
<motion.div drag dragControls={controls} dragListener={false} /><script lang="ts">
import { motion, createDragControls } from '@humanspeak/svelte-motion'
const controls = createDragControls()
</script>
<button onpointerdown={(e) => controls.start(e)}>Drag handle</button>
<motion.div drag dragControls={controls} dragListener={false} />Setting dragListener={false} prevents the element itself from initiating the drag — only the external handle will work.
The start method accepts an optional options object:
controls.start(event, { snapToCursor: true })controls.start(event, { snapToCursor: true })| Option | Description |
|---|---|
snapToCursor | Centre the element on the pointer when the drag starts |
distanceThreshold | How far, in pixels, the pointer must travel before the drag starts |
immediate | Start the drag at once, without waiting for the pointer to move (Motion 14.10). Useful to carry a drag on from another element. A press and release with no move still fires onDragStart and onDragEnd |
controls.start(event, { immediate: true })controls.start(event, { immediate: true })While dragging
Use whileDrag to animate the element while a drag gesture is active:
<motion.div
drag
whileDrag={{ scale: 1.1, boxShadow: '0 8px 24px rgba(0,0,0,0.2)' }}
/><motion.div
drag
whileDrag={{ scale: 1.1, boxShadow: '0 8px 24px rgba(0,0,0,0.2)' }}
/>Propagation
By default, drag events propagate to parent drag components. Set dragPropagation={false} to prevent this:
<motion.div drag>
<motion.div drag dragPropagation={false} />
</motion.div><motion.div drag>
<motion.div drag dragPropagation={false} />
</motion.div>Callbacks
Drag provides several lifecycle callbacks. Each receives the native PointerEvent and a DragInfo object:
<motion.div
drag
onDragStart={(event, info) => console.log('Start', info.point)}
onDrag={(event, info) => console.log('Move', info.delta)}
onDragEnd={(event, info) => console.log('End', info.velocity)}
onDragTransitionEnd={() => console.log('Momentum settled')}
/><motion.div
drag
onDragStart={(event, info) => console.log('Start', info.point)}
onDrag={(event, info) => console.log('Move', info.delta)}
onDragEnd={(event, info) => console.log('End', info.velocity)}
onDragTransitionEnd={() => console.log('Momentum settled')}
/>DragInfo
The info object passed to drag callbacks contains:
| Property | Type | Description |
|---|---|---|
point | { x, y } | Current pointer position |
delta | { x, y } | Change since the last drag event (per-frame delta) |
offset | { x, y } | Cumulative transform offset since drag start |
velocity | { x, y } | Current velocity in px/s |
Behavior
drag runs on Motion’s own drag controller, so these details match Motion:
- Default styles. A draggable element gets
user-select: none,draggable="false"and atouch-actionfor its axis:nonefordrag,pan-yfordrag="x"andpan-xfordrag="y". They’re set inline, so they win over the same properties in your CSS classes orstyle. SetdragListener={false}to opt out. - Pointer cancel. A
pointercancel(for example, the browser taking over a touch for scrolling) ends the drag like apointerup.onDragEndfires with the release velocity and momentum still runs. - Re-grabbing outside the constraints. If you catch an element while it’s outside its constraints, it moves back toward the edge as you drag, then follows the pointer at the
dragElasticrate. - Element constraints. Resizing the window, the element or the constraint element moves the element to the same relative position within the new constraints. Only the first constraint element is watched for resizes. If you swap
dragConstraintsto a different element, the new bounds apply, but resizing only the new element won’t reposition anything. - Drag controls. Every element that receives the same
dragControlsis driven bystart,cancelandstop.stop()ends a live drag with momentum andcancel()ends it without. Neither does anything once the drag is over, so neither stops an animation that’s already running after release.
Vanilla drag()
drag() makes plain elements draggable without a motion component (Motion 14.4). It takes an element, a list of elements or a CSS selector, and returns a function that removes the gesture:
<script lang="ts">
import { drag } from '@humanspeak/svelte-motion'
let track = $state<HTMLElement | null>(null)
let knob = $state<HTMLElement | null>(null)
$effect(() => {
if (!knob || !track) return
return drag(knob, { axis: 'x', constraints: track })
})
</script>
<div bind:this={track}>
<div bind:this={knob}></div>
</div><script lang="ts">
import { drag } from '@humanspeak/svelte-motion'
let track = $state<HTMLElement | null>(null)
let knob = $state<HTMLElement | null>(null)
$effect(() => {
if (!knob || !track) return
return drag(knob, { axis: 'x', constraints: track })
})
</script>
<div bind:this={track}>
<div bind:this={knob}></div>
</div>While attached, drag() sets user-select: none, touch-action (none, or pan-y/pan-x with an axis) and draggable="false" on the element. The cleanup function restores them.
Options
| Option | Type | Default | Description |
|---|---|---|---|
axis | 'x' \| 'y' | both axes | Restrict dragging to one axis |
constraints | { top?, left?, right?, bottom? } \| Element | — | Pixel bounds relative to the origin, or an element to stay within |
elastic | number \| { top?, left?, right?, bottom? } | 0.35 | How far, from 0 to 1, the element can move outside its constraints |
momentum | boolean | true | Carry the release velocity into an inertia animation |
transition | InertiaOptions | — | Options for the inertia animation on release |
snapToOrigin | boolean \| 'x' \| 'y' | false | Animate back to the origin on release |
directionLock | boolean | false | Lock to the first axis the pointer moves along |
propagation | boolean | false | Let drags start on draggable parents too |
onStart / onMove / onEnd | (event, info) => void | — | Drag lifecycle callbacks, with the same info as DragInfo |
onDirectionLock | (axis: 'x' \| 'y') => void | — | Fires when directionLock picks an axis |
onTransitionEnd | () => void | — | Fires when the release animation settles |
onMeasureConstraints | (constraints) => constraints \| void | — | Called when element constraints are measured; return a box to override them |
x | MotionValue<number> | — | Write the drag to these motion values instead of moving the element |
y | MotionValue<number> | — | Write the drag to these motion values instead of moving the element |
Headless drag
Pass x and/or y motion values (Motion 14.10) and drag() writes the gesture into them instead of moving the element. The element stays put, so a drag can drive anything, like a dial’s rotation. Values from this library’s motionValue() and useMotionValue() both work:
<script lang="ts">
import { drag, motionValue } from '@humanspeak/svelte-motion'
let dial = $state<HTMLElement | null>(null)
const x = motionValue(0)
$effect(() => {
if (!dial) return
const el = dial
const unsubscribe = x.on('change', (v) => (el.style.rotate = `${v}deg`))
const stop = drag(el, { axis: 'x', x })
return () => {
unsubscribe()
stop()
}
})
</script>
<div bind:this={dial}></div><script lang="ts">
import { drag, motionValue } from '@humanspeak/svelte-motion'
let dial = $state<HTMLElement | null>(null)
const x = motionValue(0)
$effect(() => {
if (!dial) return
const el = dial
const unsubscribe = x.on('change', (v) => (el.style.rotate = `${v}deg`))
const stop = drag(el, { axis: 'x', x })
return () => {
unsubscribe()
stop()
}
})
</script>
<div bind:this={dial}></div>With animate() and animateLayout()
The element’s x and y are motion values shared with animate() and animateLayout(). An element moved by animate() keeps its offset when a drag starts, and you can animate it again after a drag:
await animate(knob, { x: 120 })
const stop = drag(knob) // the drag continues from x: 120
// later, spring it home
animate(knob, { x: 0 }, { type: 'spring' })await animate(knob, { x: 120 })
const stop = drag(knob) // the drag continues from x: 120
// later, spring it home
animate(knob, { x: 0 }, { type: 'spring' })In a scope
Called inside a useScopeMotion or scopeMotion setup, a selector resolves within the scope’s root, callbacks run in the scope, and the gesture is removed when the scope stops:
<script lang="ts">
import { drag, useScopeMotion } from '@humanspeak/svelte-motion'
const scope = useScopeMotion(() => {
drag('.handle', { axis: 'y' })
})
</script>
<ul {@attach scope}>
<li class="handle">Only handles inside this list are draggable</li>
</ul><script lang="ts">
import { drag, useScopeMotion } from '@humanspeak/svelte-motion'
const scope = useScopeMotion(() => {
drag('.handle', { axis: 'y' })
})
</script>
<ul {@attach scope}>
<li class="handle">Only handles inside this list are draggable</li>
</ul>motion components
A motion component that already has a drag prop doesn’t need drag(); use its drag props instead. As in Motion, drag() doesn’t check for this. If you pass such an element anyway, drag() attaches a second drag gesture, and the element still moves only once: Motion’s drag lock lets one gesture at a time take the pointer, and both gestures share the element’s x and y.
Props
Drag
| Prop | Type | Default | Description |
|---|---|---|---|
drag | boolean \| 'x' \| 'y' | false | Enable dragging. true for both axes, or restrict to one axis |
dragConstraints | { top?, left?, right?, bottom? } \| HTMLElement | — | Pixel bounds or element reference to constrain drag |
dragElastic | number | 0.35 | Elasticity when overdragging. 0 = hard stop, 1 = full stretch |
dragMomentum | boolean | true | Apply momentum after release |
dragTransition | DragTransition | — | Physics configuration for momentum and boundaries |
dragSnapToOrigin | boolean | false | Spring back to starting position on release |
dragDirectionLock | boolean | false | Lock to first detected axis of movement |
dragPropagation | boolean | true | Allow drag events to bubble to parent drag elements |
dragListener | boolean | true | Enable the built-in drag listener on the element |
dragControls | DragControls | — | External controls for programmatic drag initiation |
whileDrag | MotionWhileDrag | — | Animation target while drag is active |
Callbacks
| Prop | Type | Description |
|---|---|---|
onDragStart | (event, info) => void | Fires when drag begins |
onDrag | (event, info) => void | Fires on every drag movement |
onDragEnd | (event, info) => void | Fires when drag ends |
onDirectionLock | (axis: 'x' \| 'y') => void | Fires when direction is locked |
onDragTransitionEnd | () => void | Fires when post-drag momentum settles |
DragTransition
| Property | Type | Default | Description |
|---|---|---|---|
bounceStiffness | number | 200 with elasticity, 1000000 without | Spring stiffness at constraint boundaries |
bounceDamping | number | 40 with elasticity, 10000000 without | Damping at constraint boundaries |
power | number | 0.8 | Momentum power factor |
timeConstant | number | 750 | Exponential decay time constant (ms) |
restDelta | number | 1 | Distance threshold for “at rest” |
restSpeed | number | 10 | Velocity threshold for boundary spring rest |
modifyTarget | (target: number) => number | — | Adjust the calculated inertia target |
min | number | — | Minimum value for axis |
max | number | — | Maximum value for axis |
Related
- Motion Component — Full API reference
- Variants — Define reusable animation states
- AnimatePresence — Exit animations on unmount
- Vanilla drag() example — A slider knob built on
drag() - Pinch — Pinch composes with
drag: lift one finger and the drag carries on from where the pinch left the element
Based on Motion’s drag API.