How to add event handlers on html elements by JavaScript?

Asked 19-Jul-2021
Viewed 435 times

1 Answer


Event in javaScript

This is a process in which the related code and controls are not activated automatically, it is executed by various responses of the user. In this process, the code of the program remains idle until an event (Button) (Click), etc. is called, that is, the mutual union of the hardware and software of the system is called Event.

Event handling is the process that controls events and decides what to do when an event occurs. A source is an object that generates the event. These are components like- buttons, text fields, etc. The event is generated when the state inside the source changes. A source can generate more than one event. The source has to be registered with the listener because whenever an event occurs, its notification will be received by the listener.

You can easily remove an event listener by calling the removeEventListener() a method in JavaScript.


element.addEventListener(event, function, useCapture)
event - this argument is mandatory, it takes event names like click, dblclick, mouseover, mousemove, etc.
function - also this argument is mandatory because this is executed after the event occurs.
useCapture - it is optional, it can take true and false values.


<!DOCTYPE html>

        padding:10px 30px;
<h1>addEventListener function </h1>
<button id='myBtn'>Click Me </button>
<p id='demo'></p>
var x = document.getElementById('myBtn');
x.addEventListener('mouseover', mouseoverFunction);
x.addEventListener('click', clickFunction);
x.addEventListener('mouseout', mouseoutFunction);
function mouseoverFunction() {
  document.getElementById('demo').innerHTML += 'Moused over!<br>'
function clickFunction() {
  document.getElementById('demo').innerHTML += 'Clicked!<br>'
function mouseoutFunction() {
  document.getElementById('demo').innerHTML += 'Moused out!<br>'

How to add event handlers on html elements by JavaScript?