svelte:window to track window width. What will be shown on the screen after resizing the browser window?<script> let width = 0; function updateWidth(event) { width = event.currentTarget.innerWidth; } </script> <svelte:window on:resize={updateWidth} /> <p>Window width: {width}</p>
svelte:window listens to window events and updates reactive variables.The svelte:window element listens to the window's resize event. When the window is resized, updateWidth runs and updates the width variable with the new window width. This causes the paragraph to update and show the current width.
handleScroll whenever the user scrolls the window. Which Svelte syntax is correct?function handleScroll(event) { console.log('scroll position:', window.scrollY); }
The correct syntax to listen to window events in Svelte is using <svelte:window>. Option B uses this correctly. Other options use invalid tags or syntax.
svelte:window event handler not update the variable?scrollY variable should update on scroll but it does not. Why?<script> let scrollY = 0; function onScroll(event) { scrollY = event.target.scrollY; } </script> <svelte:window on:scroll={onScroll} /> <p>Scroll position: {scrollY}</p>
event.target refers to in window scroll events.In window scroll events, event.target is the window object, but scrollY is a property of window itself, not the event target. Accessing event.target.scrollY is undefined. The correct way is to use window.scrollY.
keyPressed after pressing the 'a' key?keyPressed contain after pressing the 'a' key?<script> let keyPressed = ''; function onKeydown(event) { keyPressed = event.key; } </script> <svelte:window on:keydown={onKeydown} /> <p>Last key pressed: {keyPressed}</p>
The event.key property contains the character of the key pressed, so pressing 'a' sets keyPressed to 'a'. event.code would be 'KeyA', but that is not used here.
svelte:window instead of window.addEventListener in Svelte?svelte:window is preferred over manually adding event listeners to window in Svelte components?svelte:window is a Svelte feature that automatically adds and removes event listeners tied to the component's lifecycle. This prevents memory leaks and makes code cleaner. Manual window.addEventListener requires explicit cleanup.