AnimatePresence
AnimatePresence enables exit animations for components when they are removed from the DOM. Wrap your conditional content with AnimatePresence to animate children as they enter and exit.
<script>
import { motion, AnimatePresence } from '@humanspeak/svelte-motion'
let isVisible = $state(true)
</script>
<AnimatePresence>
{#if isVisible}
<motion.div
key="box"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
/>
{/if}
</AnimatePresence><script>
import { motion, AnimatePresence } from '@humanspeak/svelte-motion'
let isVisible = $state(true)
</script>
<AnimatePresence>
{#if isVisible}
<motion.div
key="box"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
/>
{/if}
</AnimatePresence>Existing conditional form: clone exits
The existing {#if} API remains supported:
<AnimatePresence>
{#if visible}
<motion.div key="card" exit={{ opacity: 0 }} />
{/if}
</AnimatePresence><AnimatePresence>
{#if visible}
<motion.div key="card" exit={{ opacity: 0 }} />
{/if}
</AnimatePresence>When the condition becomes false:
- The component’s last position and styles are captured
- A visual clone is created at that exact position
- The
exitanimation runs on the clone - Once complete, the clone is removed from the DOM
This approach ensures smooth exit animations even though the original Svelte component has already unmounted.
Exit clones are non-interactive (inert) and hidden from the accessibility tree. A subtree containing canvas, iframe, video, or audio is removed immediately instead of animating a clone that would lose its live bitmap, browsing context, or playback state.
Clone exits preserve unitless line-height inheritance instead of freezing every descendant’s line height to pixels. Nested text and CSS-generated ::before/::after captions keep their spacing when the exit starts and scale with font-size animations. Fixed line heights remain fixed.
Boundary removal and navigation
Exit animations run when a child is removed while its AnimatePresence boundary remains mounted. Removing the entire boundary cancels its queued and running clone exits and removes their clones and layout placeholders immediately. Cancelled clone exits do not call onExitComplete.
For example, navigating away from a SvelteKit page containing AnimatePresence does not leave that page’s exit clones over the destination. This applies to sync, wait, and popLayout modes.
To animate route changes intentionally, keep the boundary mounted in a persistent layout and change its children inside that boundary.
Owned real-node exits
Pass present and a named child snippet when the exiting element must remain the original DOM node. AnimatePresence owns the conditional rendering, holds the snippet while it exits, and removes it after the nested motion.* component reports completion.
<script lang="ts">
import {
AnimatePresence,
motion
} from '@humanspeak/svelte-motion'
let visible = $state(true)
</script>
<AnimatePresence present={visible}>
{#snippet child()}
<motion.div
animate={{ opacity: 1 }}
exit={{ opacity: 0, scale: 0.9 }}
>
This is the real node during exit.
</motion.div>
{/snippet}
</AnimatePresence><script lang="ts">
import {
AnimatePresence,
motion
} from '@humanspeak/svelte-motion'
let visible = $state(true)
</script>
<AnimatePresence present={visible}>
{#snippet child()}
<motion.div
animate={{ opacity: 1 }}
exit={{ opacity: 0, scale: 0.9 }}
>
This is the real node during exit.
</motion.div>
{/snippet}
</AnimatePresence>real DOM node
AnimatePresence owns this childExit completes before this node is removed.
Use the owned form for stateful elements, focus-sensitive interfaces, reversible exits, and integrations that need a live VisualElement or DOM node throughout the exit. It does not require a key because it owns one child.
| Behavior | {#if visible} | present={visible} |
|---|---|---|
| Exiting DOM node | Detached clone | Original node |
key requirement | Required on a direct motion.* child | Not required for the owned child |
| Rapid re-entry | New node appears while the old ghost exits | The same node reverses its exit |
| Focus, canvas, media, live state | Not retained by the clone | Retained while exit is in progress |
| VisualElement during exit | Disconnected | Live |
An owned child with nothing that exits (plain elements, or an m without LazyMotion features) leaves at once, as in Motion.
PresenceChild remains available as the lower-level primitive for custom CSS, GSAP, canvas, or other manually completed exit work.
Usage
Basic enter/exit
The most common pattern is toggling visibility with enter and exit animations:
<script lang="ts">
import { motion, AnimatePresence } from '@humanspeak/svelte-motion'
let isVisible = $state(true)
</script>
<AnimatePresence>
{#if isVisible}
<motion.div
key="modal"
initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.8 }}
transition={{ type: 'spring', stiffness: 300, damping: 25 }}
>
Modal content
</motion.div>
{/if}
</AnimatePresence>
<button onclick={() => isVisible = !isVisible}>
Toggle
</button><script lang="ts">
import { motion, AnimatePresence } from '@humanspeak/svelte-motion'
let isVisible = $state(true)
</script>
<AnimatePresence>
{#if isVisible}
<motion.div
key="modal"
initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.8 }}
transition={{ type: 'spring', stiffness: 300, damping: 25 }}
>
Modal content
</motion.div>
{/if}
</AnimatePresence>
<button onclick={() => isVisible = !isVisible}>
Toggle
</button>The key prop
When using AnimatePresence, motion components need a key prop to track their identity:
<AnimatePresence>
{#if isVisible}
<motion.div
key="unique-id"
exit={{ opacity: 0 }}
/>
{/if}
</AnimatePresence><AnimatePresence>
{#if isVisible}
<motion.div
key="unique-id"
exit={{ opacity: 0 }}
/>
{/if}
</AnimatePresence>The key is used to:
- Track which components are entering vs. exiting
- Ensure the correct exit animation plays for each component
- Handle re-entry animations correctly
Suppressing initial animation
By default, all children animate when AnimatePresence first mounts. To prevent this, set initial={false}:
<AnimatePresence initial={false}>
{#if isVisible}
<motion.div
key="box"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
/>
{/if}
</AnimatePresence><AnimatePresence initial={false}>
{#if isVisible}
<motion.div
key="box"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
/>
{/if}
</AnimatePresence>With initial={false}:
- Children present on first render skip their enter animation
- Only subsequent entries (after exits) will animate in
Exit completion callback
Use onExitComplete to run code after all exit animations finish:
<script>
function handleExitComplete() {
console.log('All exits complete!')
// Navigate, cleanup, etc.
}
</script>
<AnimatePresence onExitComplete={handleExitComplete}>
{#if isVisible}
<motion.div key="box" exit={{ opacity: 0 }} />
{/if}
</AnimatePresence><script>
function handleExitComplete() {
console.log('All exits complete!')
// Navigate, cleanup, etc.
}
</script>
<AnimatePresence onExitComplete={handleExitComplete}>
{#if isVisible}
<motion.div key="box" exit={{ opacity: 0 }} />
{/if}
</AnimatePresence>This is useful for:
- Navigation after a page transition completes
- Cleanup operations
- Triggering subsequent animations
Working with lists
AnimatePresence works with dynamic lists using Svelte’s {#each} block:
<script lang="ts">
import { motion, AnimatePresence } from '@humanspeak/svelte-motion'
let items = $state([
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
])
function removeItem(id: number) {
items = items.filter(item => item.id !== id)
}
</script>
<AnimatePresence>
{#each items as item (item.id)}
<motion.div
key={String(item.id)}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 20 }}
>
{item.text}
<button onclick={() => removeItem(item.id)}>Remove</button>
</motion.div>
{/each}
</AnimatePresence><script lang="ts">
import { motion, AnimatePresence } from '@humanspeak/svelte-motion'
let items = $state([
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' }
])
function removeItem(id: number) {
items = items.filter(item => item.id !== id)
}
</script>
<AnimatePresence>
{#each items as item (item.id)}
<motion.div
key={String(item.id)}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 20 }}
>
{item.text}
<button onclick={() => removeItem(item.id)}>Remove</button>
</motion.div>
{/each}
</AnimatePresence>Important: Use Svelte’s keyed
{#each}block ({#each items as item (item.id)}) and pass a matching stringkeyprop to the motion component.
Combining with variants
AnimatePresence works seamlessly with variants for cleaner, reusable animations:
<script lang="ts">
import { motion, AnimatePresence, type Variants } from '@humanspeak/svelte-motion'
let isVisible = $state(true)
const itemVariants: Variants = {
hidden: { opacity: 0, y: 20 },
visible: { opacity: 1, y: 0 },
exit: { opacity: 0, y: -20 }
}
</script>
<AnimatePresence>
{#if isVisible}
<motion.div
key="item"
variants={itemVariants}
initial="hidden"
animate="visible"
exit="exit"
/>
{/if}
</AnimatePresence><script lang="ts">
import { motion, AnimatePresence, type Variants } from '@humanspeak/svelte-motion'
let isVisible = $state(true)
const itemVariants: Variants = {
hidden: { opacity: 0, y: 20 },
visible: { opacity: 1, y: 0 },
exit: { opacity: 0, y: -20 }
}
</script>
<AnimatePresence>
{#if isVisible}
<motion.div
key="item"
variants={itemVariants}
initial="hidden"
animate="visible"
exit="exit"
/>
{/if}
</AnimatePresence>Exit transition configuration
You can specify a custom transition for the exit animation:
<motion.div
key="box"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{
opacity: 0,
scale: 0.8,
transition: { duration: 0.2, ease: 'easeIn' }
}}
/><motion.div
key="box"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{
opacity: 0,
scale: 0.8,
transition: { duration: 0.2, ease: 'easeIn' }
}}
/>The exit transition takes precedence over the component’s general transition prop.
popLayout positioning
With mode="popLayout", an exiting element is taken out of the layout straight away, so the elements around it reflow while it animates out. It is pinned with position: absolute exactly where it was.
It stays there even when popping it moves its container: a list anchored to the bottom of the window (a toast stack), a list centred with translate(-50%, -50%), a list inside a scaled ancestor, or a page whose scroll position is clamped because the content got shorter. Once the update is in the DOM, the element is measured again and offset back, before any layout animation measures it. This works for both the clone form and the owned present + child form.
anchorX and anchorY choose which edges of its container the exiting element is pinned by. Use anchorY="bottom" for elements positioned with bottom: 0, and anchorX="right" for elements positioned with right: 0 (in right-to-left text the two horizontal edges swap, as in Motion).
<ul class="toasts">
<AnimatePresence mode="popLayout" anchorY="bottom">
{#each toasts as toast (toast.id)}
<motion.li
key={toast.id}
layout
exit={{ opacity: 0, scale: 0.8 }}
>
{toast.message}
</motion.li>
{/each}
</AnimatePresence>
</ul><ul class="toasts">
<AnimatePresence mode="popLayout" anchorY="bottom">
{#each toasts as toast (toast.id)}
<motion.li
key={toast.id}
layout
exit={{ opacity: 0, scale: 0.8 }}
>
{toast.message}
</motion.li>
{/each}
</AnimatePresence>
</ul>The pin is a rule in an injected <style> element, appended to the head of the element’s document. Pass root to append it elsewhere, for example to a shadow root, so the rule applies inside shadow DOM.
Nested exits with propagate
A nested AnimatePresence is independent of its parent by default: when the parent’s child exits, the nested boundary’s children don’t run their own exits. Pass propagate to make them exit with the parent. The parent’s exit then waits for theirs to finish.
<AnimatePresence present={open}>
{#snippet child()}
<motion.div exit={{ opacity: 0 }}>
<AnimatePresence propagate>
{#each items as item (item.id)}
<motion.div key={item.id} exit={{ x: -20, opacity: 0 }}>
{item.label}
</motion.div>
{/each}
</AnimatePresence>
</motion.div>
{/snippet}
</AnimatePresence><AnimatePresence present={open}>
{#snippet child()}
<motion.div exit={{ opacity: 0 }}>
<AnimatePresence propagate>
{#each items as item (item.id)}
<motion.div key={item.id} exit={{ x: -20, opacity: 0 }}>
{item.label}
</motion.div>
{/each}
</AnimatePresence>
</motion.div>
{/snippet}
</AnimatePresence>propagate needs an owned outer exit: a present + child boundary (as above) or a PresenceChild. When the outer exit is a clone (a {#if} or {#each} child of AnimatePresence), the subtree is replaced by a static copy, so there is nothing nested left to animate.
Shared layout
An exiting child with a layoutId takes part in shared layout animations, as in Motion. When it leaves, it is relegated in its layoutId’s stack: the element that takes over (a newly mounted one, or an earlier one still on screen, such as the thumbnail a card opened from) animates from it, and the exiting element follows it and fades out while the new one fades in. It stays mounted until that animation ends, even without an exit prop (Motion’s MeasureLayout holds it with usePresence until safeToRemove). Closing a card shrinks it back into the thumbnail it came from.
Both forms work. A direct child keeps its projection node on its exit clone, nested motion children included; with present + child, the real element stays mounted.
<AnimatePresence>
{#if open}
<motion.div key="card" layoutId={open} class="card" />
{/if}
</AnimatePresence><AnimatePresence>
{#if open}
<motion.div key="card" layoutId={open} class="card" />
{/if}
</AnimatePresence>Exiting layout elements keep animating their layout during the exit too (for example when a popLayout exit clamps a scroll position), through the same projection node.
Latching props with present + child
A snippet reads live state. While the present + child element is held for its exit, a prop that changed on the way out (layoutId={open} going null) reaches it, where Motion re-renders the exiting child with its last props. Read a value latched while it was present instead:
<script>
import { AnimatePresence, motion } from '@humanspeak/svelte-motion'
let open = $state(null)
// The id the card was last shown with.
let shown = $state(null)
$effect.pre(() => {
if (open) shown = open
})
</script>
<AnimatePresence present={!!open}>
{#snippet child()}
<motion.div layoutId={shown} class="card" />
{/snippet}
</AnimatePresence><script>
import { AnimatePresence, motion } from '@humanspeak/svelte-motion'
let open = $state(null)
// The id the card was last shown with.
let shown = $state(null)
$effect.pre(() => {
if (open) shown = open
})
</script>
<AnimatePresence present={!!open}>
{#snippet child()}
<motion.div layoutId={shown} class="card" />
{/snippet}
</AnimatePresence>Props
AnimatePresence
| Prop | Type | Default | Description |
|---|---|---|---|
initial | boolean | true | When false, children skip their enter animation on initial mount |
mode | 'sync' \| 'wait' \| 'popLayout' | 'sync' | How entering and exiting children are coordinated |
custom | unknown | undefined | Data passed to exiting children’s dynamic variants |
onExitComplete | () => void | undefined | Callback invoked once all exit animations complete |
anchorX | 'left' \| 'right' | 'left' | With mode="popLayout", the horizontal edge an exiting element is pinned by |
anchorY | 'top' \| 'bottom' | 'top' | With mode="popLayout", the vertical edge an exiting element is pinned by |
root | HTMLElement \| ShadowRoot | document head | With mode="popLayout", where the pop <style> is appended (for example a shadow root) |
propagate | boolean | false | Exit this boundary’s children when a parent presence exits (needs an owned outer exit) |
Motion component props (for AnimatePresence)
| Prop | Type | Description |
|---|---|---|
key | string | Required. Unique identifier for tracking enter/exit state |
initial | object \| string \| false | Initial animation state |
animate | object \| string | Target animation state |
exit | object \| string | Exit animation state when component is removed |
Best practices
1. Always provide a key
Every motion component inside AnimatePresence should have a unique key:
<!-- Good -->
<motion.div key="modal" exit={{ opacity: 0 }} />
<!-- Bad - no key -->
<motion.div exit={{ opacity: 0 }} /><!-- Good -->
<motion.div key="modal" exit={{ opacity: 0 }} />
<!-- Bad - no key -->
<motion.div exit={{ opacity: 0 }} />2. Use semantic exit animations
Exit animations should feel natural and match the context:
<!-- Modal: scale down and fade -->
<motion.div
key="modal"
exit={{ opacity: 0, scale: 0.95 }}
/>
<!-- Sidebar: slide out -->
<motion.div
key="sidebar"
exit={{ x: -300 }}
/>
<!-- Toast: slide up and fade -->
<motion.div
key="toast"
exit={{ opacity: 0, y: -20 }}
/><!-- Modal: scale down and fade -->
<motion.div
key="modal"
exit={{ opacity: 0, scale: 0.95 }}
/>
<!-- Sidebar: slide out -->
<motion.div
key="sidebar"
exit={{ x: -300 }}
/>
<!-- Toast: slide up and fade -->
<motion.div
key="toast"
exit={{ opacity: 0, y: -20 }}
/>3. Match enter and exit
For visual consistency, exit animations often mirror enter animations:
<motion.div
key="item"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 20 }} <!-- Same as initial -->
/><motion.div
key="item"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 20 }} <!-- Same as initial -->
/>4. Consider performance
Keep exit animations short (200-400ms) to avoid UI feeling sluggish:
<motion.div
key="item"
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
/><motion.div
key="item"
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
/>Common patterns
Page transitions
<script>
import { page } from '$app/stores'
</script>
<AnimatePresence>
{#key $page.url.pathname}
<motion.main
key={$page.url.pathname}
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
>
<slot />
</motion.main>
{/key}
</AnimatePresence><script>
import { page } from '$app/stores'
</script>
<AnimatePresence>
{#key $page.url.pathname}
<motion.main
key={$page.url.pathname}
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
>
<slot />
</motion.main>
{/key}
</AnimatePresence>Modal/Dialog
<AnimatePresence>
{#if showModal}
<!-- Backdrop -->
<motion.div
key="backdrop"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
class="backdrop"
onclick={() => showModal = false}
/>
<!-- Modal -->
<motion.div
key="modal"
initial={{ opacity: 0, scale: 0.9, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.9, y: 20 }}
class="modal"
>
Modal content
</motion.div>
{/if}
</AnimatePresence><AnimatePresence>
{#if showModal}
<!-- Backdrop -->
<motion.div
key="backdrop"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
class="backdrop"
onclick={() => showModal = false}
/>
<!-- Modal -->
<motion.div
key="modal"
initial={{ opacity: 0, scale: 0.9, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.9, y: 20 }}
class="modal"
>
Modal content
</motion.div>
{/if}
</AnimatePresence>Notification stack
<AnimatePresence>
{#each notifications as notification (notification.id)}
<motion.div
key={notification.id}
initial={{ opacity: 0, x: 100 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 100 }}
transition={{ type: 'spring', stiffness: 500, damping: 30 }}
>
{notification.message}
</motion.div>
{/each}
</AnimatePresence><AnimatePresence>
{#each notifications as notification (notification.id)}
<motion.div
key={notification.id}
initial={{ opacity: 0, x: 100 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 100 }}
transition={{ type: 'spring', stiffness: 500, damping: 30 }}
>
{notification.message}
</motion.div>
{/each}
</AnimatePresence>Related
- Variants - Define reusable animation states
- Examples - See AnimatePresence in action
- Motion Component - Full API reference
Based on Motion’s AnimatePresence API.