Each HTML element has a method called addEventListener() that allows you to register an event handler that will be invoked whenever a specific event occurs. In simple terms, you use an event handler to execute code when a particular event occurs.
htmlElement.addEventListener(event, eventHandler);
An event can be click, keydown, etc.
eventHandler
is the function that is called when an event occurs. It can be an anonymous function or just a normal function.
Let's understand the entire process of adding an event handler to an HTML element with the help of an example:
Suppose there is a button, and you want to display a popup whenever a user clicks on that button.
<button id="btn">Click Me</button>
To attach an event listener to that button, you have to select that button using the document.getElementById()
, document.querySelector()
, or methods like this.
let btn = document.getElementById('btn');
After that, call the addEventListener() method on the selected button. Pass 'click' as the first argument and an anonymous function as the second parameter.
btn.addEventListener('click', function(event){ alert('button is clicked'); });
If you click on the button, a popup will be displayed.
Note: If you want to use the event handler method elsewhere, then use a normal JavaScript function.
let btn = document.getElementById('btn'); function eventHandler(event){ alert('button is clicked'); } btn.addEventListener('click', eventHandler);