0
0
Svelteframework~5 mins

DOM event listeners (on:click) in Svelte - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does on:click do in Svelte?

on:click listens for a click event on an element and runs the specified code or function when the element is clicked.

Click to reveal answer
beginner
How do you attach a click event listener to a button in Svelte?

Use on:click inside the button tag like this: <button on:click={handleClick}>Click me</button>.

Click to reveal answer
intermediate
Can you use inline code with on:click in Svelte? Give an example.

Yes, you can write inline code directly: <button on:click={() => alert('Clicked!')}>Click</button>.

Click to reveal answer
intermediate
What happens if you add multiple on:click handlers to the same element in Svelte?

Svelte will run all the handlers in the order they appear when the element is clicked.

Click to reveal answer
beginner
Why is using on:click better than adding event listeners manually in Svelte?

Because on:click is declarative, simpler, and Svelte automatically cleans up listeners when components are removed, preventing bugs.

Click to reveal answer
What is the correct way to listen for a click event on a button in Svelte?
A<button on:click={handleClick}>Click me</button>
B<button onclick='handleClick()'>Click me</button>
C<button listen:click={handleClick}>Click me</button>
D<button @click={handleClick}>Click me</button>
What does on:click={() => alert('Hi')} do?
ADoes nothing
BRuns alert('Hi') immediately on page load
CRuns alert('Hi') when the element is clicked
DPrevents the click event
Can you attach more than one on:click handler to the same element in Svelte?
ANo, only one handler is allowed
BNo, it causes an error
CYes, but only the first runs
DYes, all handlers run in order
What is a benefit of using on:click in Svelte over manual event listeners?
AAutomatic cleanup when component unmounts
BIt uses less memory
CIt disables other events
DIt works only on buttons
Which of these is NOT a valid way to write a click handler in Svelte?
A<button on:click={() =&gt; doSomething()}>Click</button>
B<button on:click='doSomething()'>Click</button>
C<button on:click={doSomething}>Click</button>
D<button on:click={() =&gt; alert('Hi')}>Click</button>
Explain how to use on:click in Svelte to run a function when a button is clicked.
Think about how you tell Svelte to listen for clicks.
You got /3 concepts.
    Describe the advantages of using on:click in Svelte compared to adding event listeners manually.
    Consider what happens when components are removed.
    You got /3 concepts.