JavaScript events and event handlers: addEventListener
verified on 7 September 2026 · 2 min
Events are actions the user can trigger, such as clicking a button, typing text into a form, and so on. In JavaScript, we use event handlers to run code in response to those events.
Common events in JavaScript
There are plenty of common events used regularly in JavaScript. Here are a few examples:
- click: fired when the user clicks an element
- mouseover: fired when the user moves the mouse over an element
- submit: fired when the user submits a form
- focus: fired when the user focuses an element (by clicking into a form field, for example)
Many other events can fire while the user interacts with the page, such as “change”, “keyup”, “keydown” and so on. You will find a fuller list of events here: https://www.gekkode.com/developpement/comprendre-et-travailler-avec-les-evenements-en-javascript/
Adding an event handler to an element
There are several ways to attach an event handler to a DOM element. The first is to use the property on the element itself. For example, to add a click handler to a button:
const button = document.querySelector('button');
button.onclick = function() {
console.log('Bouton cliqué');
}You can also use the addEventListener method, which lets you attach several handlers to the same element:
const input = document.querySelector('input');
input.addEventListener('focus', function() {
console.log('Input focus');
});
input.addEventListener('blur', function() {
console.log('Input blur');
});And there is the removeEventListener method to take a handler off an element:
// our anonymous function
const maFonctionAnonyme = function() {
console.log("Le bouton a été cliqué");
}
// We add our event
document.getElementById('monBouton')
.addEventListener('click', maFonctionAnonyme);
// Later in the code, we remove this event for one reason or another
document.getElementById('monBouton')
.removeEventListener('click', maFonctionAnonyme);Note that the function passed as a parameter must be the very same instance as the one added to the element. An anonymous function passed directly to addEventListener therefore cannot be removed later: keep a reference in a variable, as above.
In this example, the “click” event handler bound to the “maFonctionAnonyme” function is removed from the button.
Conclusion
Using events and event handlers, you can create real-time interactions with your website and make it more dynamic and pleasant to use. The next chapter presents modules and imports/exports (ES6), which split the code into files, classes, for their part, are detailed in the article on classes in JavaScript.