> For the complete documentation index, see [llms.txt](https://web-dev-guide.wishtack.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://web-dev-guide.wishtack.io/dom/events.md).

# Events

Modern browsers can trigger **hundreds of types of events** *(\~500)*.

<https://developer.mozilla.org/en-US/docs/Web/Events>

{% embed url="<https://developer.mozilla.org/en-US/docs/Web/Events>" %}

These event types can be of any kind:

* User interaction : click, input change, keypress, drag & drop etc...
* Geolocation,
* Device motion,
* Network status,
* ...

## Registering Event Listeners

These events can be intercepted by adding an **event listener** to the corresponding event type.

An event listener is a JavaScript function that **will be called whenever the event is triggered**.

In most cases, the listener function will take as first argument, **the event object** with different properties and data depending on the event type and the event itself.

### Listening to a click

```javascript
const button = document.querySelector('button');

let clickCount = 0;

/* Increment the counter on every click. */
button.addEventListener('click', () => clickCount++);
```

### Listening to keyboard

```javascript
document.addEventListener('keydown', event => {
    if (event.ctrlKey === true
        && event.key === 'x'
        /* This will show a confirmation dialog and return true if user confirms. */
        && confirm('Do you really want to remove the selected blog post?')) {
        removeSelectedItem();
    }
});
```

### Watching geolocation

```javascript
navigator.geolocation.watchPosition(position => {
    console.log(`
    Accuracy: ${position.coords.accuracy},
    Latitude: ${position.coords.latitude},
    Longitude: ${position.coords.longitude}
    `);
});
```

{% hint style="info" %}
Some functions like `watchPosition` will prompt the user for his consent before allowing access to geolocation.
{% endhint %}

## Removing Event Listeners

In order to avoid **side effects**, **dead code** and **memory leaks** it is important to think about clearing your event registrations by removing the listeners.

This can be done differently depending on the event type.

#### `removeEventListener`

```javascript
const listener = () => clickCount++;

button.addEventListener('click', listener);

button.removeEventListener('click', listener);
```

#### `clear...`

```javascript
const watchId = navigator.geolocation.watchPosition(...);
navigator.geolocation.clearWatch(watchId);

const interval = setInterval(() => console.log(clickCount), 1000);
clearInterval(interval);
```

## Events bubbling & capturing

<http://javascript.info/bubbling-and-capturing>

{% embed url="<http://javascript.info/bubbling-and-capturing>" %}
