0
0
Svelteframework~15 mins

svelte:window for window events - Mini Project: Build & Apply

Choose your learning style9 modes available
Using <code>svelte:window</code> to Track Window Resize
📖 Scenario: You are building a simple Svelte app that shows the current width of the browser window. This helps users see how wide their screen is in real time.
🎯 Goal: Create a Svelte component that listens to window resize events using svelte:window and updates the displayed window width dynamically.
📋 What You'll Learn
Create a variable width to store the window width
Use svelte:window with the on:resize event
Update width when the window resizes
Display the current width in the component
💡 Why This Matters
🌍 Real World
Tracking window size is common in responsive web design to adjust layouts or content dynamically.
💼 Career
Understanding how to handle window events in Svelte is useful for building interactive, accessible web apps that respond to user environment changes.
Progress0 / 4 steps
1
Set up the width variable
Create a variable called width and set it to window.innerWidth to get the initial window width.
Svelte
Hint

Use let width = window.innerWidth to get the current width of the browser window.

2
Add svelte:window with on:resize event
Add a <svelte:window on:resize={handleResize}></svelte:window> tag to listen for window resize events. Define a function called handleResize that updates width to window.innerWidth.
Svelte
Hint

Define handleResize to update width. Use <svelte:window on:resize={handleResize}> to listen for resize.

3
Display the current window width
Add a <p> tag that shows the text Window width: {width}px so users can see the current width.
Svelte
Hint

Use <p>Window width: {width}px</p> to show the width.

4
Make the component accessible and responsive
Add an aria-live="polite" attribute to the <p> tag so screen readers announce width changes politely.
Svelte
Hint

Add aria-live="polite" to the paragraph to improve accessibility.