Add an Event Handler

To add an event handler to an event of an element, you use the addEventListener() method of the element object:

element.addEventListener(type,eventListener);Code language: CSS (css)

Suppose that you have a button with the class .btn:

<button class="btn">Subscribe</button>Code language: HTML, XML (xml)

To attach an event handler to the click event, you use the following:

First, define an event handler:

function clickHandler(event) {
   console.log('Button Clicked');
}Code language: JavaScript (javascript)

Then, use the addEventListener() method of the button element:

const btn = document.querySelector('.btn');
btn.addEventListener('click', clickHandler);Code language: JavaScript (javascript)

If you’re not resuing the event handler function, you can use an anonymous function as an event handler:

const btn = document.querySelector('.btn');
btn.addEventListener('click', function(event){
   console.log('Button Clicked');
});Code language: JavaScript (javascript)

Most modern web browsers support the addEventListener() method. However, IE8 uses the attachEvent() method instead.

If you need to support IE8, you can create a helper function:

function addEvent(el, type, handler) {
  el.attachEvent ?
    el.attachEvent('on' + type, handler) :
    el.addEventListener(type, handler);
}Code language: JavaScript (javascript)

To add an event handler to the click event of the button element, you use the following:

addEvent(btn, 'click', function (event) {
  console.log('Button Clicked');
});Code language: JavaScript (javascript)
Was this tutorial helpful ?