Modern browsers can trigger hundreds of types of events(~500).
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();
}
});