Chapter 4

Using Directives

IN THIS CHAPTER

Bullet Listening for and handling events

Bullet Forwarding events

Bullet Binding attributes

Bullet Creating transitions

“Dreaming or awake, we perceive only events that have meaning to us.”

—JANE ROBERTS

Directives are special attributes that are used by Svelte to bind data, bind events, animate elements, and more. In this chapter, you'll learn about directives and how to use them to make things happen in your component.

Listening for Events with on:

The on: directive can be used with elements to listen for DOM events and to assign JavaScript functions to handle those events. The basic syntax of the on: directive is

on:eventname={handler}

The event name is the name of any DOM event, such as click, change, or submit. The handler is the name of a function or an arrow function.

Basic event handling

Any function defined at the top level of your <script> block can be accessed using :on. Listing 4-1 shows an example of listening for the semicolon key and displaying a message when it's pressed.

LISTING 4-1: Listening for a Key Event

<script> function alertMe() { alert( ...

Get JavaScript All-in-One For Dummies now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.