In the previous lesson (HTML DOM Events) we categorized some of the most used DOM events into five categories. In this lesson, we will learn how to react when such events happen using JavaScript.
There are two ways to react to DOM events:
- By attaching the required event in the HTML Element itself (which we will learn now).
- By using Event Listeners (which we will learn in the next lesson).
How can we react to DOM events? 🤔
We can react to DOM events in JavaScript by attaching the event that we want to react to, inside the desired HTML Tag just like how we did with attributes. After that, we provide a function as a value to the event which gets called every time the event is executed.
The function which we provide to the event is called an Event Handler.
Example: Let’s say you want to react to the click event of a button element. What we do is, we attach the word onclick to the button element and provide a function that gets executed every time the button element is clicked.
Examples on reacting to DOM events 😋
The following are examples from each event category that we discussed in our previous lesson (HTML DOM Events):
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.
Reacting to onload event ✅
The onload event happens when the content inside the given HTML element, where the event is attached, is loaded.
Here, we attach the onload event in our body tag and when all the content inside our body tag is loaded, our loadFunction() event handler will execute.
Note: We generally use the onload event with the body tag as, inside that, is where we keep all our viewable HTML content.
Example
<!DOCTYPE html>
<html>
<head>
<title>On Load Event</title>
</head>
<body onload="loadFunction()">
<h1>
A function will fire immediately after this document has finished loading.
</h1>
<script>
function loadFunction() {
console.log("Document loaded.");
alert("Document loaded");
}
</script>
</body>
</html>
Output
Reacting to onclick event 🖱
The onclick event happens when a user clicks on the HTML Element where the onclick event is attached.
We attach the onclick event on any HTML element where we want to click on and react to it. Here, after the user clicks on the button, the showText() event handler will be executed.
Note: We generally use the onclick event with the button tag but we can use it with most of the available HTML elements too.
Example
<!DOCTYPE html>
<html>
<head>
<title>On Click Event</title>
</head>
<body>
<button onclick="showText()">Click Me</button>
<p id="text"></p>
<script>
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
Reacting to onkeyup event 🎹
The onkeyup event happens when the user, after pressing a key on their keyboard releases it.
Here, we attach the onkeyup event on the input HTML element and after each key is pressed and released, the printText() event handler gets executed.
Note: We use the onkeyup event with elements like input, textarea, etc. where content can be typed on.
Example
<!DOCTYPE html>
<html>
<head>
<title>On Key Up Event</title>
</head>
<body>
<label htmlFor="inputField">Type Something: </label>
<input type="text" id="inputField" onkeyup="printText()" />
<p id="text"></p>
<script>
function printText() {
const inputElement = document.getElementById("inputField");
const textElement = document.getElementById("text");
// Displaying the value obtained from "inputElement" after each "keyup" event.
textElement.innerText = `${inputElement.value}`;
}
</script>
</body>
</html>
Output
Reacting to onchange event ✏
The onchange event happens when the value of the HTML element, where the event is attached, is changed.
Here, we attach the onchange event on the select HTML element. After the user selects a new option, the value of the select element changes and the changeFunc() event handler gets executed.
Note: We use the onchange event mostly with elements like select, input, etc. whose content can be changed upon user interaction.
Example
<!DOCTYPE html>
<html>
<head>
<title>On Change Event</title>
</head>
<body>
<label htmlFor="selectLang">Select your favorite language: </label>
<select id="selectLang" onchange="changeFunc()">
<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>
// When the user selects a new option, the "changeFunc()" will execute.
function changeFunc() {
const selectElement = document.getElementById("selectLang");
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
Reacting to onsubmit event 👍
The onsubmit event happens when a form is submitted. Therefore, the onsubmit event can be attached to only the form element.
Here, we attach the onsubmit event on the form HTML element. After the user submits the form, the formSubmission() event handler gets executed.
Note: The action attribute defines where to go to after form submission. So, for this example, we just redirected to the same page i.e. “/onsubmit.html“.
Example
<!DOCTYPE html>
<html>
<head>
<title>On 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" onsubmit="formSubmission()">
<label htmlFor="ambition">What do you want to be?: </label>
<input type="text" id="ambition" />
<input type="submit" />
</form>
<script>
// When the user submits the form, the "formSubmission()" function will execute.
function formSubmission() {
alert("Form Submitted");
}
</script>
</body>
</html>
Output: Before Form Submission
Output: After Form Submission
Reacting to ondrag event 💪
The ondrag event happens when the HTML element, where the event is attached, is dragged. But to make an element draggable, we need to set it’s draggable attribute to true.
The ondrag event when paired with ondrop helps us to add amazing drag and drop features in our website. We will be doing those in our upcoming lessons.
Here, we attach the ondrag event on the div HTML element. After the user drags the element, the dragFunc() event handler gets executed.
Example
<!DOCTYPE html>
<html>
<head>
<title>On 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" ondrag="dragFunc()" draggable="true">
<p id="dragText">Drag Me.</p>
</div>
<script>
// The "dragFunc()" gets executed when the "div" element is dragged.
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
Attaching event handlers to specified events is one way to react to an event in JavaScript. In the next lesson, we will learn about Event Listeners, another way of reacting to an event. 😎