Discover how a simple tag can save you from messy event code and bugs!
Why svelte:window for window events? - Purpose & Use Cases
Imagine you want to run some code every time the browser window resizes or the user scrolls. You try to add event listeners manually in your code to watch for these changes.
Manually adding and removing window event listeners is tricky. You might forget to clean them up, causing bugs or slowdowns. It's easy to write repetitive code that clutters your app and makes it hard to maintain.
The svelte:window tag lets you listen to window events directly in your component markup. It automatically handles adding and removing listeners, keeping your code clean and safe.
import { onMount } from 'svelte'; onMount(() => { window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); });
<svelte:window on:resize={handleResize} />You can easily react to window changes like resize or scroll with simple, readable code that stays bug-free and maintainable.
Think about a photo gallery that adjusts its layout when the browser window changes size. Using svelte:window, you can update the layout instantly without messy event code.
Manually managing window events is error-prone and repetitive.
svelte:window simplifies listening to window events in components.
This leads to cleaner, safer, and easier-to-read code.
Practice
svelte:window in a Svelte component?Solution
Step 1: Understand
svelte:windowusagesvelte:windowis a special element in Svelte used to listen to events on the browser window object.Step 2: Identify the correct purpose
It does not create windows or style elements but listens to events like resize or scroll on the window.Final Answer:
To listen to events on the browser window like resize or scroll -> Option CQuick Check:
svelte:windowlistens to window events [OK]
svelte:window listens to window events only [OK]- Thinking it creates or styles windows
- Confusing with component state management
- Using it to listen to DOM element events
svelte:window?Solution
Step 1: Recall correct event binding syntax in Svelte
In Svelte, event listeners useon:eventName={handler}syntax.Step 2: Apply to
The correct way to listen to window resize issvelte:window<svelte:window on:resize={handleResize} />.Final Answer:
<svelte:window on:resize={handleResize} /> -> Option BQuick Check:
Useon:eventonsvelte:window[OK]
on:event syntax on svelte:window [OK]- Using HTML
windowtag which doesn't exist - Trying to bind event with
bind:instead ofon: - Attaching events to
divinstead ofsvelte:window
width after resizing the browser window?
<script>
let width = 0;
function updateWidth(event) {
width = event.currentTarget.innerWidth;
}
</script>
<svelte:window on:resize={updateWidth} />
<p>Window width: {width}</p>
Solution
Step 1: Understand the event handler logic
TheupdateWidthfunction setswidthtoevent.currentTarget.innerWidth, which is the window's width.Step 2: Recognize
On every resize event,svelte:windowevent behaviorupdateWidthruns, updatingwidthreactively.Final Answer:
It updates to the current window width on every resize -> Option AQuick Check:
Resize triggers updateWidth, updating width [OK]
- Assuming width never changes without explicit initialization
- Confusing event.currentTarget with event.target
- Thinking event.currentTarget is undefined in this context
<script>
let scrollY = 0;
function onScroll() {
scrollY = window.scrollY;
}
</script>
<svelte:window on:scroll={onScroll}></svelte:window>
<p>Scroll position: {scrollY}</p>
Solution
Step 1: Check
svelte:windowtag usagesvelte:windowis a special element that must be self-closing when used to listen to events.Step 2: Identify the tag error
The code uses an opening and closing tag<svelte:window></svelte:window>, which is invalid syntax for this element.Final Answer:
Using <svelte:window> with a closing tag instead of self-closing -> Option DQuick Check:
svelte:windowmust be self-closing [OK]
svelte:window when listening to events [OK]- Trying to use opening and closing tags for
svelte:window - Thinking
bind:is needed for event values - Assuming
window.scrollYis inaccessible in handler
svelte:window. Which code snippet correctly updates both values on resize events?Solution
Step 1: Understand event object properties
In window resize events,event.currentTargetandevent.targetmay not reliably provideinnerWidthandinnerHeight. Usingwindow.innerWidthandwindow.innerHeightis safer.Step 2: Check each option
<script> let width = 0, height = 0; function updateSize(event) { width = event.currentTarget.innerWidth; height = event.currentTarget.innerHeight; } </script> <svelte:window on:resize={updateSize} />usesevent.currentTargetwhich may not always be the window.<script> let width = 0, height = 0; function updateSize() { width = window.innerWidth; height = window.innerHeight; } </script> <svelte:window on:resize={updateSize} />useswindow.innerWidthandwindow.innerHeightdirectly, which is correct.<script> let width = 0, height = 0; <svelte:window bind:innerWidth={width} bind:innerHeight={height} /> </script>tries to bind non-bindable properties.<script> let width = 0, height = 0; function updateSize(event) { width = event.target.innerWidth; height = event.target.innerHeight; } </script> <svelte:window on:resize={updateSize} />usesevent.targetwhich is unreliable.Final Answer:
Use window.innerWidth and window.innerHeight inside the handler -> Option AQuick Check:
Access window size viawindow.innerWidthin handler [OK]
window.innerWidth inside handler, not event properties [OK]- Using event.currentTarget or event.target for window size
- Trying to bind window properties directly
- Assuming event object always has innerWidth/innerHeight
Ready to prove it?
Pass the test and this pattern moves unknown
