How to add an event listener in JavaScript
Adding event listeners is fundamental to creating interactive web applications that respond to user actions like clicks, key presses, and form submissions.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented thousands of event listeners in interactive components.
From my 25 years of development experience, the most robust method is using addEventListener() which provides better control and flexibility than inline event handlers.
This modern approach supports multiple listeners and prevents conflicts.
Use addEventListener() to attach event handlers to DOM elements with proper event management.
const button = document.getElementById('myButton')
button.addEventListener('click', function(event) {
console.log('Button clicked!')
})
The addEventListener() method takes the event type (‘click’) as the first parameter and a callback function as the second. The callback receives an event object containing details about the triggered event. This method allows multiple listeners for the same event and provides better memory management than older approaches like onclick.
Best Practice Note:
This is the standard approach we use throughout CoreUI components for reliable event handling.
Always use addEventListener() over inline handlers for better code organization and the ability to easily remove listeners later with removeEventListener().



