The svelte:window tag lets you listen to events on the browser window, like resizing or scrolling, so your app can react to changes outside its own elements.
svelte:window for window events
<svelte:window on:eventName={handler} />Replace eventName with the actual window event like resize, scroll, or keydown.
The handler is a function that runs when the event happens.
handleResize function whenever the window is resized.<svelte:window on:resize={handleResize} />handleScroll function whenever the user scrolls the page.<svelte:window on:scroll={handleScroll} />handleKeydown function when any key is pressed anywhere in the window.<svelte:window on:keydown={handleKeydown} />This component shows the current window width and height. It updates the values whenever the window is resized using svelte:window and the resize event.
<script> let width = 0; let height = 0; function updateSize() { width = window.innerWidth; height = window.innerHeight; } // Initialize size on component load updateSize(); </script> <svelte:window on:resize={updateSize} /> <main> <h1>Window size</h1> <p>Width: {width}px</p> <p>Height: {height}px</p> </main>
You don't need to manually add or remove event listeners; Svelte handles that for you.
Use svelte:window only for events on the window object, not on specific elements.
Remember to keep event handlers fast and simple to avoid slowing down your app.
svelte:window lets you listen to browser window events easily.
Use it to react to changes like resizing, scrolling, or key presses anywhere in the window.
Svelte manages event listeners automatically, so your code stays clean.