Skip to main content
The <svelte:window> element allows you to add event listeners to the window object without worrying about removing them when the component is destroyed, or checking for the existence of window when server-side rendering.
This element may only appear at the top level of your component — it cannot be inside a block or element.

Event Listeners

You can add any valid window event listener using the on directive:

Common window events

  • onresize - Window is resized
  • onscroll - Window is scrolled
  • onfocus - Window gains focus
  • onblur - Window loses focus
  • onkeydown - Key is pressed
  • onkeyup - Key is released
  • onmousemove - Mouse moves
  • onbeforeunload - Before window unloads

Bindings

You can bind to the following window properties:
number
The inner width of the window in pixels.
number
The inner height of the window in pixels.
number
The outer width of the window in pixels.
number
The outer height of the window in pixels.
number
The horizontal scroll position in pixels. Can be set to scroll the window.
number
The vertical scroll position in pixels. Can be set to scroll the window.
boolean
Whether the browser is online. An alias for window.navigator.onLine.
number
The ratio of physical pixels to CSS pixels for the current display.

Usage

Track window dimensions

Scroll control

The page will not be scrolled to the initial value to avoid accessibility issues. Only subsequent changes to the bound variable of scrollX and scrollY will cause scrolling.If you have a legitimate reason to scroll when the component is rendered, call scrollTo() in an $effect.

Track online status

Multiple bindings and events