Home » JavaScript » JavaScript Event Listeners

JavaScript Event Listeners

JavaScript Event Listene - The addEventListener() method is used to add an event handler to any specified element. If there are more than one event handlers, then this method attaches an event handler to an element without overwriting existing event handlers. The event listener can be removed easily if you want to, by using removeEventListener() method.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Event Listner </title>
</head>
<body>
<button id="myBtn">Click Me</button>
<script>
// Defining custom functions
function firstFunction() {
alert("The first function executed successfully!");
}
function secondFunction() {
alert("The second function executed successfully");
}
// Selecting button element
var btn = document.getElementById("myBtn");
// Assigning event handlers to the button
btn.onclick = firstFunction;
btn.onclick = secondFunction; // This one overwrite the first
</script>
</body>
</html>

Output

JavaScript Event Listner

Mutile event listeners

The addEventListener() method is used to assign multiple event listeners. It attaches an event handler to the specified element. This method as described earlier, doesn't overwrite the previous event handlers, thus is a good practice to use this instead of normal event handlers.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Event Listner </title>
</head>
<body>
<button id="Btn">Click Me</button>
<script>
// Defining custom functions
function firstFunction() {
alert("The first function executed successfully!");
}
function secondFunction() {
alert("The second function executed successfully");
}
// Selecting button element
var btn = document.getElementById("Btn");
// Assigning event listeners to the button
btn.addEventListener("click", firstFunction);
btn.addEventListener("click", secondFunction);
</script>
</body>
</html>

Output

JavaScript Event Listner

Remove Event Listeners

The removeEventListener() method is used to remove an event listener which were attached by addEventListener() method. In the example below, first an event listener is attached by addEventListener() method, then removeEventListener() method is used to remove that assigned event listener.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript remove Event Listner </title>
</head>
<body>
<button id="button">Click Me</button>
<script>
// Defining function
function greetWorld() {
alert("Hello World!");
}
// Selecting button element
var button = document.getElementById("button");
// Attaching event listener
button.addEventListener("click", greetWorld);
// Removing event listener
button.removeEventListener("click", greetWorld);
</script>
</body>
</html>

Output

JavaScript remove Event Listner

Note : If you click the "Click Me" button nothing will happen, since event listener is removed.












Follow Us: