How to add an Event Listener in JavaScript

To listen for an event on any HTML DOM element in JavaScript, use the addEventListener() method.

 

The addEventListener() Syntax

The addEventListener() method accepts three arguments, the first two are required and the third is optional.

 

addEventListener(event, function[, useCapture])

 

  • event - The event to listen for. Here are some common events in JavaScript:
    • change
    • click
    • mouseover
    • keydown
  • function - the function to handle the event when it happens
  • useCapture - boolean value for handling the event in the capturing or in the bubbling phase (optional).

 

Adding an Event Listener to an Element

To demonstrate using an event listener in JavaScript lets create one for a click event on a button with an ID.

 

<button id="foo">Click me</button>
document.getElementById('foo').addEventListener('click', function() {
  alert(this.innerText);
});

 

In the example above, when the button with the ID of foo is clicked a function that alerts the user with the innerText of the button they just clicked runs.

 

Here is a different example demonstrating an onchange event with a named function.

 

<input type="file" name="image" id="image">
function addImage() {
  console.log(this.files[0].name);
}

document.getElementById('image').addEventListener('change', addImage);
bar.jpg

 

In the above example when the user selects a file the event is handled by the addImage() function, which in this case simply gets the name of the file.

 

How to Remove an Event Listener

To remove an event listener, use the removeEventListener() method. The first argument is the type of event to remove and the second is the name of the handler function. As a result, you can only remove event listeners that have named functions.

 

<button id="foo">Click me</button>
function btnClick() {
  alert(this.innerText);
}

document.getElementById('foo').addEventListener('click', btnClick);

document.getElementById('foo').removeEventListener('click', btnClick);

 

Here is a more comprehensive example demonstrating the removal of the click event listener and handler after the user has clicked a button once using a custom function.

 

<button id="foo">Click me</button>
function removeEventListenerByID(id, event, func) {
  document.getElementById(id).removeEventListener(event, func);
}

function btnClick() {
  alert(this.innerText);

  removeEventListenerByID(this.id, 'click', btnClick);
}

document.getElementById('foo').addEventListener('click', btnClick);

Related Tutorials

 thumbnail

JavaScript Events

February 26, 2021