0
0
SvelteConceptBeginner · 3 min read

What is svelte:document in Svelte: Usage and Examples

svelte:document is a special Svelte element that lets you listen to events on the whole HTML document inside a component. It works like attaching event listeners directly to document, enabling you to react to global events such as key presses or clicks outside your component.
⚙️

How It Works

Imagine you want to know when someone clicks anywhere on the page, not just inside your component. Normally, your component only knows about events inside its own area. svelte:document acts like a bridge that connects your component to the entire HTML document.

When you use svelte:document, you can listen for events like keydown or click happening anywhere on the page. It's like putting a microphone on the whole document and reacting when something happens.

This is useful because sometimes you need to respond to user actions outside your component, such as closing a dropdown when clicking elsewhere or handling keyboard shortcuts globally.

💻

Example

This example listens for the Escape key anywhere on the page and shows a message when pressed.

svelte
<script>
  let message = '';

  function handleEscape(event) {
    if (event.key === 'Escape') {
      message = 'Escape key pressed!';
    }
  }
</script>

<svelte:document on:keydown={handleEscape} />

<p>{message}</p>
Output
Escape key pressed! (appears when Escape key is pressed anywhere on the page)
🎯

When to Use

Use svelte:document when you need to listen to events that happen outside your component's area but still want to react inside your component. Common cases include:

  • Closing modals or dropdowns when clicking outside them
  • Handling global keyboard shortcuts or key presses
  • Detecting clicks anywhere on the page for analytics or UI updates

It helps keep your component aware of the whole page's user interactions without manually adding and removing event listeners on document.

Key Points

  • svelte:document lets components listen to events on the entire HTML document.
  • It is useful for global event handling like keyboard shortcuts or clicks outside components.
  • It automatically manages adding and removing event listeners for you.
  • Use it to keep your UI responsive to user actions anywhere on the page.

Key Takeaways

svelte:document allows listening to global document events inside Svelte components.
It is ideal for handling keyboard shortcuts and clicks outside component boundaries.
It simplifies event listener management by automatically adding and removing them.
Use it to make your component respond to user actions anywhere on the page.