0
0
Svelteframework~3 mins

Why svelte:window for window events? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple tag can save you from messy event code and bugs!

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
import { onMount } from 'svelte';

onMount(() => { window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); });
After
<svelte:window on:resize={handleResize} />
What It Enables

You can easily react to window changes like resize or scroll with simple, readable code that stays bug-free and maintainable.

Real Life Example

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.

Key Takeaways

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.