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 />
mode · live running

// 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>
mode · live running

// 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: the x/y the drag started from.
  • elastic: the resolved per-axis, per-side elastic.
  • getAxisMotionValue(axis): the x or y motion value the drag writes to.
  • getProps(): the drag’s options, e.g. drag for 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 })
OptionDescription
snapToCursorCentre the element on the pointer when the drag starts
distanceThresholdHow far, in pixels, the pointer must travel before the drag starts
immediateStart 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:

PropertyTypeDescription
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 a touch-action for its axis: none for drag, pan-y for drag="x" and pan-x for drag="y". They’re set inline, so they win over the same properties in your CSS classes or style. Set dragListener={false} to opt out.
  • Pointer cancel. A pointercancel (for example, the browser taking over a touch for scrolling) ends the drag like a pointerup. onDragEnd fires 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 dragElastic rate.
  • 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 dragConstraints to 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 dragControls is driven by start, cancel and stop. stop() ends a live drag with momentum and cancel() 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

OptionTypeDefaultDescription
axis'x' \| 'y'both axesRestrict dragging to one axis
constraints{ top?, left?, right?, bottom? } \| Element—Pixel bounds relative to the origin, or an element to stay within
elasticnumber \| { top?, left?, right?, bottom? }0.35How far, from 0 to 1, the element can move outside its constraints
momentumbooleantrueCarry the release velocity into an inertia animation
transitionInertiaOptions—Options for the inertia animation on release
snapToOriginboolean \| 'x' \| 'y'falseAnimate back to the origin on release
directionLockbooleanfalseLock to the first axis the pointer moves along
propagationbooleanfalseLet 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
xMotionValue<number>—Write the drag to these motion values instead of moving the element
yMotionValue<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

PropTypeDefaultDescription
dragboolean \| 'x' \| 'y'falseEnable dragging. true for both axes, or restrict to one axis
dragConstraints{ top?, left?, right?, bottom? } \| HTMLElement—Pixel bounds or element reference to constrain drag
dragElasticnumber0.35Elasticity when overdragging. 0 = hard stop, 1 = full stretch
dragMomentumbooleantrueApply momentum after release
dragTransitionDragTransition—Physics configuration for momentum and boundaries
dragSnapToOriginbooleanfalseSpring back to starting position on release
dragDirectionLockbooleanfalseLock to first detected axis of movement
dragPropagationbooleantrueAllow drag events to bubble to parent drag elements
dragListenerbooleantrueEnable the built-in drag listener on the element
dragControlsDragControls—External controls for programmatic drag initiation
whileDragMotionWhileDrag—Animation target while drag is active

Callbacks

PropTypeDescription
onDragStart(event, info) => voidFires when drag begins
onDrag(event, info) => voidFires on every drag movement
onDragEnd(event, info) => voidFires when drag ends
onDirectionLock(axis: 'x' \| 'y') => voidFires when direction is locked
onDragTransitionEnd() => voidFires when post-drag momentum settles

DragTransition

PropertyTypeDefaultDescription
bounceStiffnessnumber200 with elasticity, 1000000 withoutSpring stiffness at constraint boundaries
bounceDampingnumber40 with elasticity, 10000000 withoutDamping at constraint boundaries
powernumber0.8Momentum power factor
timeConstantnumber750Exponential decay time constant (ms)
restDeltanumber1Distance threshold for “at rest”
restSpeednumber10Velocity threshold for boundary spring rest
modifyTarget(target: number) => number—Adjust the calculated inertia target
minnumber—Minimum value for axis
maxnumber—Maximum value for axis

Related


Based on Motion’s drag API.