<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 theon directive:
Common window events
onresize- Window is resizedonscroll- Window is scrolledonfocus- Window gains focusonblur- Window loses focusonkeydown- Key is pressedonkeyup- Key is releasedonmousemove- Mouse movesonbeforeunload- Before window unloads
Bindings
You can bind to the following window properties:The inner width of the window in pixels.
The inner height of the window in pixels.
The outer width of the window in pixels.
The outer height of the window in pixels.
The horizontal scroll position in pixels. Can be set to scroll the window.
The vertical scroll position in pixels. Can be set to scroll the window.
Whether the browser is online. An alias for
window.navigator.onLine.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.