The svelte:body tag lets you listen to events happening anywhere on the whole page, not just inside your component. This helps you catch clicks or key presses even outside your app area.
0
0
svelte:body for body events
Introduction
You want to close a dropdown menu when the user clicks anywhere outside it.
You need to detect keyboard shortcuts no matter where the user is on the page.
You want to track clicks on the page to log user activity.
You want to handle global scroll or resize events on the whole page.
You want to detect clicks outside a modal to close it.
Syntax
Svelte
<svelte:body on:eventName={handler} />Replace eventName with the actual event like click, keydown, etc.
The handler function receives the event object as usual.
Examples
Listen for any click on the whole page and run
handleClick.Svelte
<svelte:body on:click={handleClick} />Listen for any key press anywhere on the page.
Svelte
<svelte:body on:keydown={handleKeydown} />Logs the mouse position whenever the user clicks anywhere on the page.
Svelte
<script> function logClick(event) { console.log('Clicked at', event.clientX, event.clientY); } </script> <svelte:body on:click={logClick} />
Sample Program
This component shows a message that updates when you click anywhere on the page, even outside the component area.
Svelte
<script> let message = 'Click anywhere on the page'; function handleBodyClick() { message = 'You clicked somewhere on the page!'; } </script> <p>{message}</p> <svelte:body on:click={handleBodyClick} />
OutputSuccess
Important Notes
Using svelte:body is great for global event handling without adding event listeners manually.
Remember to keep handlers efficient to avoid slowing down the page.
You can also use svelte:window for events on the window object, which is different from svelte:body.
Summary
svelte:body lets you listen to events on the whole page's body element.
Use it to catch clicks, key presses, or other events anywhere on the page.
It helps manage global interactions easily inside your Svelte components.