A Basic Introduction to Event Handling in Svelte for Beginners by@smpnjn

A Basic Introduction to Event Handling in Svelte for Beginners

Read on Terminal Reader
Open TLDR
react to story with heart
react to story with light
react to story with boat
react to story with money
Svelte allows for all the events you'd typically find in Vanilla Javascript. In this guide, we'll look at how to get started with Svelt events. We'll start with a basic example of a simple counter. The counter will increase the counter any time the mouse moves over the button. Any Javascript event you want to use can be used in the place of 'click' events. You can use other Javascript events, like `click` or `event` data, like 'scroll` or 'hover' data.
image
Johnny Simpson HackerNoon profile picture

Johnny Simpson

Product, Engineering, Web

github social iconinstagram social iconlinkedin social icontwitter social icon


Events in Svelte are quite intuitive and easy to use. In this guide, we'll look at how to get started with Svelte events.


It is assumed you have a good understanding of Javascript for this guide. If you are brand new to Svelte, it might make sense to read my guide on creating your first Svelte application before beginning.


What are events in Svelte?

When we create new components in Svelte, we will usually want them to do certain things when users interact with them - for example, hover over them, or click on them. Svelte allows for all the events you'd typically find in Vanilla Javascript.


Let's start with a basic example. The component below creates a simple counter:


<script>
    // we write export let to say that this is a property
    // that means we can change it later!
    let x = 0;
    const addToCounter = function() {
        ++x;
    }
</script>

<button id="counter">{x}</button>


Every time the user clicks on the button, we want addToCounter to fire, which will increase x by 1, and display it within the button itself. To do that, we will add an event.


Here is the event we'll need to add for when the user clicks the button:


<button id="counter" on:click={addToCounter}>{x}</button>


We use {} in Svelte to indicate that the value of this property is Javascript. Any valid Javascript event can be used in the place of click.


For example, the below will increase the counter any time the mouse moves over the button:


<button id="counter" on:mouseover={addToCounter}>{x}</button>


Similarly, you can use other Javascript events, like click, scroll, hover, mouseup, pointerup, pointerdown, mousedown, etc. These are just examples - but any Javascript event you want to use can be used.


How to Access Event Data in your Svelte Events?

Sometimes, we want to access e or event data when a user interacts with our component. The event object carries a lot of useful information about the event fired. To do that, we simply need to change our handler into a function.


For example, let’s retrieve the click position of the button, and display that to the user this time.


<script>
    // we write export let to say that this is a property
    // that means we can change it later!
    let x = 0;
	let click = [0, 0]
    
    const addToCounter = function(e) {
	    click[0] = e.clientX;
	    click[1] = e.clientY;
        ++x;
    }
</script>

<button id="counter" on:click={(e) => { addToCounter(e) }}>
    Clicked {x} times, last at {click[0]}, {click[1]}
</button>


Here, we store e.clientX and e.clientY in a variable, and display that to the user any time the button is clicked.


For those that don't know, e.clientX and e.clientY both refer to an aspect of the position of the cursor when the event was fired.


Svelte is naturally reactive, so the button will update automatically with the latest data, whenever it is clicked.


Svelte Event Forwarding

Event forwarding is whenever a user triggers an event on a child component, which we want to handle in the parent component. It is essentially saying that this component can have a specific event, but it is not handled here.


Looking at our prior example, we can set up event forwarding first by setting up events that can be forwarded on the child component.


Let's say we create a component in a file called Comp.svelte which looks like the one below. One button is clickable, while the other is not.


<button on:click>
    Click me, I am a button
</button>
<button>
    I am unclickable. Ignore me.
</button>


Here we are saying that the first button has a valid on:click event. This is useful since it lets us define certain elements within a component with valid events which can be forwarded upwards. In our parent, then, we can import our button, like so:


<script>
    import Comp from './Comp.svelte';

    let x = 0;
    const addToCounter = () => {
        ++x;
    }
</script>

<Comp on:click={addToCounter} />


Now when the user clicks on the first button within Comp, it will fire the on:click event and run the addToCounter function. If we removed on:click from Comp.svelte completely, then no event would trigger despite defining on:click on our Comp component.


That means we can not only define that a child should have an event attached to it, but we can also define which specific elements have that event, by adding it to the child component itself. This gives us a lot of flexibility.


Final thoughts

Svelte events are straightforward to use, and the fact that they follow the same naming conventions as Vanilla Javascript events makes them incredibly simple to use.


In this guide, we've covered the basics so you can get started.


Also Published Here

For more Svelte content, try my other articles here

react to story with heart
react to story with light
react to story with boat
react to story with money

Related Stories

L O A D I N G
. . . comments & more!