0
0
Svelteframework~5 mins

svelte:window for window events

Choose your learning style9 modes available
Introduction

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.

You want to update your layout when the browser window size changes.
You want to detect when the user scrolls the page to show or hide something.
You want to listen for keyboard events globally, like pressing Escape to close a modal.
You want to track when the window gains or loses focus.
You want to react to window-level events like online/offline status changes.
Syntax
Svelte
<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.

Examples
Runs handleResize function whenever the window is resized.
Svelte
<svelte:window on:resize={handleResize} />
Runs handleScroll function whenever the user scrolls the page.
Svelte
<svelte:window on:scroll={handleScroll} />
Runs handleKeydown function when any key is pressed anywhere in the window.
Svelte
<svelte:window on:keydown={handleKeydown} />
Sample Program

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.

Svelte
<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>
OutputSuccess
Important Notes

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.

Summary

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.