Events

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

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

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

let clickCount = 0;

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

Listening to keyboard

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

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

Some functions like watchPosition will prompt the user for his consent before allowing access to geolocation.

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

const listener = () => clickCount++;

button.addEventListener('click', listener);

button.removeEventListener('click', listener);

clear...

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

Last updated