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.