Events
useWindowDimensions
Track and react to window dimension changes with the useWindowDimensions hook.
Return Values
Name | Type | Description |
---|---|---|
width | number | Returns the current window width. |
height | number | Returns the current window height. |
loading | boolean | Returns true if the window dimensions are not yet available. |
Source Code
import { onMount } from "svelte"; const useWindowDimensions = () => { let width = $state(0); let height = $state(0); let loading = $state(true); const handleResize = () => { width = window.innerWidth; height = window.innerHeight; } onMount(() => { window.addEventListener('resize', handleResize); handleResize(); loading = false; return () => window.removeEventListener('resize', handleResize); }) return { get width() { return width }, get height() { return height }, get loading() { return loading } } } export default useWindowDimensions;
<script> import useWindowDimensions from "./useWindowDimensions.svelte"; let dimensions = useWindowDimensions(); </script> {#snippet box({label, value})} <div class="box box-{label.toLowerCase()}"> <span class="label">{label}</span> <span class="value">{value}px</span> </div> {/snippet} <div class="container"> {#if !dimensions.loading} <span class="title">Window Dimensions</span> <div class="box-list"> {@render box({label: "Width", value: dimensions.width })} {@render box({label: "Height", value: dimensions.height })} </div> {/if} </div> <style> .container { height:130px; display: flex; flex-direction:column; justify-content:center; align-items:center; gap:20px; } .title { font-weight:700; font-size:24px; } .box-list { display:flex; align-self:stretch; justify-content:center; gap:25px; } .box { background-color:rgba(255,255,255,.05); display:flex; flex-direction:column; gap:5px; padding:15px; border-radius:5px; flex-basis:150px; } .box .label { text-transform:uppercase; letter-spacing:1px; font-weight:700; text-transform:uppercase; font-size:12px; color:rgba(255,255,255,.8); } .box .value { font-weight:700; font-size:16px; } </style>