An Event Listener in JavaScript is a method that listens to events as they occur and allows us to react to it by attaching Event Handlers to it. We can listen to specific events in the JavaScript DOM using the addEventListener() method.
The addEventListener() method listens to a given specific event and attaches an Event Handler which is called whenever that event occurs. An Event Handler is a function that reacts to an event.
Syntax
element.addEventListener(event_name, event_handler_function)
Parameters
- event_name : It is required. It must contain the name of the event that we are listening to. Eg: “click”, “change”, “submit”, “mouseover”, etc.
- event_handler_function : It is required. It must contain the Event Handler function that reacts to the given event. It is called whenever the event given in event_name occurs.
Note: We can attach multiple addEventListener() methods to the same HTML Element in JavaScript.
Note: We can attach multiple addEventListener() methods that listens to the same events in JavaScript. Eg: Two Event Listeners for two “submit” events.
Examples using addEventListener() method
The following are examples from each event category that we discussed in our previous lessons (HTML DOM Events) and (Reacting to DOM Events):
- click event 🖱
- load event 😵
- keyup event 🎹
- change event ✏
- submit event ✅
- drag event 💪
As you can see, we did not write “onClick“, we removed the word “on” and just wrote “click“. When using an addEventListener() method, we don’t prepend the “on” word in front of an event.
Note: We cannot cover all the events in just one lesson. So, we have made a separate chapter for you called JS DOM Events as you can see in the left menu bar where we cover all the events that we listed down.
JavaScript addEventListener() method on a click event 🖱
A click event happens when a user clicks on the HTML Element where we attached an addEventListener() method listening to a “click” event.
Whenever a “click” event occurs, the addEventListener() method listens to it and immediately calls the attached event handler function.
Example
<!DOCTYPE html>
<html>
<head>
<title>Click Event</title>
</head>
<body>
<button id="button">Click Me</button>
<p id="text"></p>
<script>
const button = document.getElementById("button");
// Attach an event listener that listens to "click" events and calls the "showText" event handler when it occurs.
button.addEventListener("click", showText);
// Event Handler Function.
function showText() {
const textElement = document.getElementById("text");
// Writing the text "I Love Javascript." in Italic using the "<em>" tag.
textElement.innerHTML = "<em>I Love Javascript.</em>";
}
</script>
</body>
</html>
Output: Before clicking
Output: After Clicking
JavaScript addEventListener() method on a load event 😵
The onload event happens when the content inside the given HTML element, where the addEventListener() method is attached, is loaded.
In the example below, when our entire browser window is loaded, the addEventListener() method calls the attached event handler function.
Note: We can also define the Event Handler function inside our addEventListener() method itself, as given below.
Example
<!DOCTYPE html>
<html>
<head>
<title>Load Event</title>
</head>
<body id="body">
<h1>
A function will fire immediately after this document has finished loading.
</h1>
<script>
// NOTE: We cannot listen to "load" events using "addEventListener()" by attaching an "id" on the "body" element because the element would not have been loaded yet.
// When the browser "window" gets "loaded", call the event handler function attached.
// We can also use an event handler by defining it inside the "addEventListener()" method itself, as given below.
window.addEventListener("load", () => {
console.log("Document loaded.");
alert("Document loaded");
});
</script>
</body>
</html>
Output
JavaScript addEventListener() method on a keyup event 🎹
A keyup event happens when the user, after pressing a key on their keyboard releases it.
Here, whenever a “keyup” event occurs, the addEventListener() method listens to it and immediately calls the attached event handler function.
Note: We use the keyup event with elements like input, textarea, etc. where content can be typed on.
Example
<!DOCTYPE html>
<html>
<head>
<title>Key Up Event</title>
</head>
<body>
<label htmlFor="inputField">Type Something: </label>
<input type="text" id="inputField" />
<p id="text"></p>
<script>
const inputElement = document.getElementById("inputField");
// Attach an event listener to "inputElement" that listens to "keyup" events and calls the "printText" event handler when it occurs.
inputElement.addEventListener("keyup", printText);
// Event Handler Function
function printText() {
const textElement = document.getElementById("text");
// Displaying the value obtained from "inputElement" after each "keyup" event.
textElement.innerText = `${inputElement.value}`;
}
</script>
</body>
</html>
Output
JavaScript addEventListener() method on a change event ✏
A change event happens when the value of the HTML element, where we attached an addEventListener() method listening to a “change” event, is changed.
Here, after the user selects a new option, the value of the select element changes, which triggers a “change” event. Then, the addEventListener() method listens to it and immediately calls the attached event handler function.
Note: We use the change event with elements like select, input, etc. whose content can be changed upon user interaction.
Example
<!DOCTYPE html>
<html>
<head>
<title>Change Event</title>
</head>
<body>
<label htmlFor="selectLang">Select your favorite language: </label>
<select id="selectLang">
<option value="C">C</option>
<option value="C++">C++</option>
<option value="Javascript">Javascript</option>
<option value="Python">Python</option>
</select>
<p id="text"></p>
<script>
const selectElement = document.getElementById("selectLang");
// Attach an event listener to "selectElement" that listens to "change" events and calls the "changeFunc" event handler when it occurs.
selectElement.addEventListener("change", changeFunc);
// Event Handler Function
function changeFunc() {
const textElement = document.getElementById("text");
// Displaying the value obtained from "selectElement" after the user selects a new option.
textElement.innerText = `${selectElement.value}`;
}
</script>
</body>
</html>
Output: Before value is changed
Output: After value is changed/new option is selected
JavaScript addEventListener() method on a submit event ✅
The submit event happens when a form is submitted. In the example below, whenever the form is submitted, the addEventListener() method listens to it and calls the event handler function.
Example
<!DOCTYPE html>
<html>
<head>
<title>Submit Event</title>
</head>
<body>
<!--
Put the location of this file which is "/onsubmit.html" in the "action" attribute
otherwise you cannot see the "formSubmission()" function's results.
-->
<form action="/onsubmit.html" id="formSubmit">
<label htmlFor="ambition">What do you want to be?: </label>
<input type="text" id="ambition" />
<input type="submit" />
</form>
<script>
const formElement = document.getElementById("formSubmit");
// Attach an event listener to "formElement" that listens to "submit" events and calls the "formSubmission" event handler when it occurs.
formElement.addEventListener("submit", formSubmission);
// Event Handler Function
function formSubmission() {
alert("Form Submitted");
}
</script>
</body>
</html>
Output: Before Form Submission
Output: After Form Submission
JavaScript addEventListener() method on a drag event 💪
The ondrag event happens when an HTML element is dragged. But to make an element draggable, we need to set it’s draggable attribute to true.
In the example below, whenever the div element is dragged, the addEventListener() method listens to it and calls the attached event handler function.
Example
<!DOCTYPE html>
<html>
<head>
<title>Drag Event</title>
<style>
.drag-box {
border: 1px solid gray;
background-color: lightgreen;
padding: 6px;
margin-right: 10px;
width: 200px;
}
.drag-box p {
text-align: center;
}
</style>
</head>
<body>
<div class="drag-box" draggable="true" id="dragBox">
<p id="dragText">Drag Me.</p>
</div>
<script>
const dragElement = document.getElementById("dragBox");
// Attach an event listener to "dragElement" that listens to "drag" events and calls the "dragFunc" event handler when it occurs.
dragElement.addEventListener("drag", dragFunc);
// Event Handler Function
function dragFunc() {
const dragText = document.getElementById("dragText");
// After dragging, change the "dragText" element's innerText.
dragText.innerText = "Help Me, I'm being dragged.";
}
</script>
</body>
</html>
Output: Before Dragging
Output: After Dragging
Using Multiple Event Listeners in JavaScript 🤯
We can attach multiple addEventListener() methods to the same HTML element, that listens to the same events.
Here, we have two Event Listeners for two “click” events on the same button element. The first event listener attaches the showText() event handler while the second attaches the showAlert() event handler.
Also, here, both showText() and showAlert() runs simultaneously at the almost exact same time but the output from the alert() function always shows first in JavaScript.
Example
<!DOCTYPE html>
<html>
<head>
<title>Click Event</title>
</head>
<body>
<button id="button">Click Me</button>
<p id="text"></p>
<script>
const button = document.getElementById("button");
// Attach two event listeners that listens to the same "click" events.
button.addEventListener("click", showText);
button.addEventListener("click", showAlert);
// First Event Handler Function.
function showText() {
const textElement = document.getElementById("text");
// Writing the text "I Love Javascript." in Italic using the "<em>" tag.
textElement.innerHTML = "<em>I Love Javascript.</em>";
}
// Second Event Handler Function.
// The "alert()" method always runs first, even if it is attached later than "showText".
function showAlert() {
alert("aa");
}
</script>
</body>
</html>
Output: Before Clicking
Output: After Clicking
Why use addEventListener() method? 🤔
You might be wondering, in our previous lesson, we just attached the events ( onclick, onsubmit, etc. ) inline in our HTML elements. So, why even bother using an addEventListener() method.
The answer is that attaching events inline can decrease code readability when your webpage grows and you have to write more lines of code. When there are more lines of code, it becomes difficult for you to search and find which events are attached where.
With using addEventListener(), you can find out to which events you are listening to pretty easily even if the number of lines of code grows because all the event listening code is either inside your <script/> tag or in a separate JavaScript file.
In this way, we can write more modular and scalable event listeners that can scale as your web application grows. 😎 Using events is one of the most important features a JavaScript Developer has to know.