EventsInteractivity
useWindowFocus
Monitors window focus changes. This Svelte hook lets your application react to whether the browser window is in focus or not.
Return Values
Name | Type | Description |
---|---|---|
value | boolean | Indicates whether the window is in focus ( |
Source Code
import { onMount } from 'svelte'; export const useWindowFocus = () => { let value = $state(true); const checkFocus = () => { value = document.visibilityState === 'visible'; }; onMount(() => { document.addEventListener('visibilitychange', checkFocus); checkFocus(); }); return { get value() { return value; }, }; };
Window Focused ✅
<script lang="ts"> import { useWindowFocus } from './useWindowFocus.svelte'; let focused = useWindowFocus(); </script> <div class="container"> <span class="box" class:focused={focused.value}> <span>Window {focused.value ? 'Focused' : 'Unfocused'}</span> <span>{focused.value ? '✅' : '❌'}</span> </span> </div> <style lang="scss"> .container { display: flex; justify-content: center; align-items: center; } .box { border: 1px solid rgba(255, 255, 255, 0.05); padding: 2rem 3rem; background-color: rgba(255, 255, 255, 0.05); border-radius: 5px; font-weight: 700; --col: 238, 72, 72; background-color: rgba(var(--col), 0.2); color: rgb(var(--col)); } .box.focused { --col: 66, 221, 105; } </style>