# 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>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://web-dev-guide.wishtack.io/dom/events.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
