Learn to Code via Tutorials on Repl.it!

← Back to all posts
Svelte Web Framework Tutorial #3 - Events
h
xfinnbar (149)

Requirements

For you to be able to follow along with this guide, you'll need to understand:

What are events?

Remember that on:click event we used in the last tutorial? That was an event. Events are used to do something in a parent component when a thing happens in one of its child components.

Listening for events

When we use a component or HTML element, we can add the on:eventname attribute to listen for an event, passing in a JavaScript function.

<button on:click={() => alert("Button clicked!")}>Click here</button>

Creating events for components

Let's make a button inside a div that changes the div's color when it is clicked. The button will be in a separate component to the div. Take a look at this example. https://Svelte-Events-Example.xfinnbar.repl.co.

First, I'll create the basic component and HTML structure.

src/pages/index.svelte:

<script>
import  ChangeColorButton  from  '../ChangeColorButton.svelte'
</script>

<div  style="width: 500px; height: 500px;">
<ChangeColorButton />
</div>

src/ChangeColorButton.svelte:

<button>Click me to change the color of the div!</button>

Next, I'll add an on:click event listener to the button:

<script>
function sendEvent()  {
	// We'll do this next
}
</script>
<button on:click={sendEvent}>Click me to change the color of the div!</button>

And dispatch an event called changecolor to the parent component (index.svelte):

<script>

import  { createEventDispatcher }  from  'svelte';

const dispatch = createEventDispatcher();

function sendEvent()  {
	dispatch('changecolor');
}
</script>

<button on:click={sendEvent}>Click me to change the color of the div!</button>

src/pages/index.svelte:

And finally listen for it in the parent component, changing the color of the div:
You need to remove the comments in the HTML bit as they are not valid.

<script>

$: color =  "blue"; // Reactively declare the color variable

import  ChangeColorButton  from  '../ChangeColorButton.svelte'

function doStuff()  {
	if  (color ==  "blue")  {
		color =  "green"
	}  else  {
		color =  "blue"
	}
}
</script>

<div  style="width: 500px; height: 500px; background-color: {color};"> // Use reactivity to sync color with a variable
<ChangeColorButton on:changecolor={doStuff} /> // Listen for event
</div>

Thanks for reading!

If you enjoyed the tutorial, please upvote it. To be notified when the next tutorial is published, comment and I will mention you when the next one is out.