# Events

Events are used to signal that something in the DOM has happened. Some events are user-generated, such as mouse or keyboard events, while others are generated by side effects such as videos being paused or an animation that has finished running.

![](https://4254577312-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MDnC_qISWkd4BnR0CPu%2Fsync%2F445780cce5fe5eebf201cd734a98d0d240813c12.jpg?generation=1596439575177766\&alt=media)

## Click

The most intuitive event is perhaps the `click` event. It is fired when a user clicks on an element inside the DOM. Events are passed as arguments to the click handler.

Let's `alert` a string when a user presses the `Howdy` button.

```
<html>
    <button id="greeting">Howdy</button>
</html>
```

To receive the `click` event when the user press `Howdy` we need to register an event listener. Listeners are functions that are scheduled to run when an event is fired. Just like `setTimeout` and `setInterval`.

```
const greetingButton = document.getElementById('greeting');
```

First we select the element that we want to listen for the event on.

```
greetingButton.addEventListener('click', (event) => {
    alert('... partner!');
});
```

Next we add an event listener that alerts our greeting when the event is fired.

## Keypress

Another class of events that are typically fired are the ones associated with keypresses. A keypress usually fires the following events:

1. When the key is first depressed, the `keydown` event is sent.
2. If the key is not a modifier key (Shift etc.), the `keypress` event is sent.
3. When the user releases the key, the `keyup` event is sent.

Each key has a unique `keyCode` property that represents it. We use the `keyCode` to determine which key was pressed.

| Key | Code |
| --- | ---- |
| a   | 65   |
| b   | 66   |
| c   | 67   |
| ... | ...  |
| ←   | 37   |
| .→  | 38   |
| .↑  | 39   |
| .↓  | 40   |
| ... | ...  |
| F1  | 112  |
| F2  | 113  |
| F3  | 114  |

Imagine that we want to `alert` when one of the arrow keys (`↑`, `↓`, `←`, `→`) are pressed down (`keydown`) anywhere within the DOM.

```
document.addEventListener('keydown', (event) => {
    if (event.keyCode > 36 && event.keyCode < 41) {
        alert\('You pressed an arrow key.'\);  
    }
});
```

We register an event handler that can distinguish between arrow keys from all the other keys. To do so we check if the `keyCode` on the `event` lies between 36 and 41.
