Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use Event Handlers in Svelte 2


    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.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    Instructor: 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.

    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.

    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.

    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.