What is addEventListner?

·

1 min read

addEventListener is a method in JavaScript that allows you to attach an event listener function to an element in the Document Object Model (DOM).

The method takes two arguments: the first argument is the type of event you want to listen for. Click and mouseover are really common examples here. The second argument is the function that should be called when the event occurs.

Here is an example.

const button = document.querySelector('button');

button.addEventListener('click', () => {
  console.log("button is clicked");
});

In the example above, the selector 'button' is used to select the first button element in the document.

To choose the element, you can select from CSS style selector as well.

//select from id
const button = document.querySelector('#my-button');
//select from class
const button = document.querySelector('.my-button');