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().


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to set focus on an input field after rendering in React
How to set focus on an input field after rendering in React

What is Double Question Mark in JavaScript?
What is Double Question Mark in JavaScript?

How to migrate CoreUI React Templates to Vite
How to migrate CoreUI React Templates to Vite

How to Open Link in a New Tab in HTML?
How to Open Link in a New Tab in HTML?

Answers by CoreUI Core Team