Autoplay

    Use Event Handlers in Svelte

    Andrew SmithAndrew Smith
    sveltesvelte
    javascriptJavaScript

    In this lesson you will learn how to attach Event Handlers to buttons and input fields. Event handlers normally follows the on:[event] format. If you are making use of two way binding you should use bind: instead, for example an input field could use bind:value.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 Here, we have this app component that renders a UI for us. It has two data properties, counter and message. We can change the state by updating its value in the data method. We change counter to 10. We should now have 10 items.

    00:14 Let's add an on-click event to the add button. Inside the event handler, let's update the counter state by a call-in set with the value of counter = counter + 1. Let's copy this for the remove button and - 1 from the counter instead. If we click the add, the number of items increase.

    00:33 If we click remove, the number decrease. Let's take a look at the input. Input provides an on-input event which fires each time the input changes. Inside of this event, we will set the value of message to equal the value of the input field. We can now type a value in the input field and see the message update.

    00:54 Now let's take a look at the bind directive. Here, we will bind a value of the input field to the message data property. Now if we type in the field same as before, the message should update.

    Discuss

    Discuss