Consider a Svelte component that uses a clickOutside action to close a dropdown menu when clicking outside it.
What is the expected behavior when the user clicks outside the dropdown?
<script> import { clickOutside } from './actions.js'; let open = true; function close() { open = false; } </script> <div use:clickOutside={close}> {#if open} <p>Dropdown content</p> {/if} </div>
Think about what a click-outside action is designed to detect.
The clickOutside action listens for clicks outside the element it is applied to. When such a click happens, it calls the close function, which sets open to false, closing the dropdown.
You want to add a tooltip action that shows a message when hovering over a button.
Which syntax correctly passes the message 'Hello!' to the tooltip action?
Remember how to pass string parameters to Svelte actions.
In Svelte, to pass a string parameter to an action, you use curly braces with a string literal inside, like {'Hello!'}. Option A uses this correct syntax.
Examine the following Svelte action code for click-outside. Why does the menu not close when clicking outside?
export function clickOutside(node, callback) { const handleClick = event => { if (!node.contains(event.target)) { callback(); } }; document.addEventListener('click', handleClick); return { destroy() { document.removeEventListener('click', handleClick); } }; } <script> import { clickOutside } from './actions.js'; let open = true; function close() { open = false; } </script> <div use:clickOutside={close}> {#if open} <p>Menu content</p> {/if} </div>
Consider how Svelte reactivity works with functions called outside component scope.
The callback close sets open = false, but since it is called from outside Svelte's reactive context, the component does not update. To fix this, the callback should be wrapped in a Svelte reactive statement or use a store.
Given this Svelte component with a tooltip action that changes text on hover, what tooltip text is shown after the second hover?
<script> import { tooltip } from './actions.js'; let message = 'First'; function update() { message = 'Second'; } </script> <button use:tooltip={message} on:mouseenter={update}>Hover me</button>
Think about when the action receives updated parameters.
The tooltip action receives the initial message value 'First' when the component mounts. Changing message later does not update the action unless the action handles parameter updates explicitly. So the tooltip stays 'First'.
In a Svelte action that adds a global click event listener to detect clicks outside an element, why must you remove the listener when the element is destroyed?
Think about what happens if event listeners accumulate over time.
If event listeners are not removed when the element is destroyed, they remain active and consume memory. This can cause memory leaks and multiple listeners firing unexpectedly, leading to bugs and performance issues.