0
0
Svelteframework~5 mins

svelte:body for body events - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is svelte:body used for in Svelte?

svelte:body lets you listen to events on the document body directly from a Svelte component.

This is useful when you want to catch events like clicks or key presses anywhere on the page, not just inside your component.

Click to reveal answer
beginner
How do you add a click event listener on the document body using svelte:body?
<svelte:body on:click={handleClick} />

This code runs handleClick whenever the user clicks anywhere on the page.

Click to reveal answer
intermediate
Why might you prefer svelte:body over adding event listeners manually in onMount?

svelte:body automatically adds and removes the event listener when the component mounts and unmounts.

This means less code and fewer chances to forget cleanup, which helps avoid bugs.

Click to reveal answer
intermediate
Can you listen to multiple events on svelte:body at once? How?

Yes! You can add multiple event listeners by repeating on:event attributes:

<svelte:body on:click={handleClick} on:keydown={handleKeydown} />
Click to reveal answer
advanced
What happens if you use svelte:body inside multiple components on the same page?

Each component adds its own event listeners to the body.

All listeners will run when the event happens, so be careful to avoid conflicts or duplicated work.

Click to reveal answer
What does <svelte:body on:click={handleClick} /> do?
AListens for clicks anywhere on the page
BListens for clicks only inside the component
CAdds a click listener to a button
DPrevents clicks on the body
Why is svelte:body better than manually adding event listeners in onMount?
AIt runs faster
BIt automatically cleans up listeners when the component unmounts
CIt only works for click events
DIt disables other event listeners
Can you listen to keyboard events on the body using svelte:body?
AOnly inside input fields
BNo, only mouse events work
CYes, by using <code>on:keydown</code> or similar
DOnly if you add extra libraries
What happens if multiple components use svelte:body to listen to the same event?
AAll their event handlers run when the event fires
BOnly the first component's handler runs
CThe event is blocked
DAn error occurs
Which of these is a correct way to listen for a scroll event on the body in Svelte?
Adocument.body.scroll = handleScroll
B&lt;div on:scroll={handleScroll} /&gt;
Cwindow.addEventListener('scroll', handleScroll)
D&lt;svelte:body on:scroll={handleScroll} /&gt;
Explain how svelte:body helps manage event listeners on the document body in a Svelte app.
Think about how you would catch clicks anywhere on the page from inside a component.
You got /4 concepts.
    Describe a scenario where using svelte:body is better than adding event listeners manually in lifecycle functions.
    Consider global keyboard shortcuts or clicks outside a modal.
    You got /4 concepts.