Introduction
Event handling is a cornerstone of front-end development, enabling developers to respond to user interactions and other actions occurring within the DOM. In this guide, you will learn about:
- What events are and their useful properties.
- Some of the most commonly used browser events.
Event Basics
Events are actions or occurrences that happen within the DOM, and they can be triggered by user interactions, browser actions, or even code. For instance:
- A user clicking a button triggers a
clickevent. - Typing in a text field triggers an
inputevent. - Loading the initial HTML document triggers a
DOMContentLoadedevent.
Whenever an event occurs, an event object is created. This object contains various properties that provide details about the event. For example:
document.querySelector("button").addEventListener("click", (event) => {
console.log(event.target); // Logs the button element that was clicked
});
For a comprehensive list of event properties, visit the MDN Event Reference.
Common Events
1. Click
The click event is triggered whenever a user clicks on an element, such as a button:
document.querySelector("button").addEventListener("click", () => {
console.log("Button clicked!");
});
2. Input
The input event fires whenever the value of an input field changes:
document.querySelector("input").addEventListener("input", (event) => {
console.log(event.target.value); // Logs the current input value
});
3. Change
The change event fires when a user commits a change, such as selecting an option or clicking away from an input field:
document.querySelector("select").addEventListener("change", (event) => {
console.log(event.target.value); // Logs the selected option
});
4. Submit
The submit event is triggered when a form is submitted:
document.querySelector("form").addEventListener("submit", (event) => {
event.preventDefault(); // Prevents the default form submission
console.log("Form submitted!");
});
5. DOMContentLoaded
The DOMContentLoaded event fires when the HTML document is fully loaded and parsed but before stylesheets and images are loaded:
document.addEventListener("DOMContentLoaded", () => {
console.log("DOM fully loaded and parsed!");
});
This event is useful for running JavaScript that interacts with the DOM without waiting for all assets to load.
What You Learned
In this guide, you explored:
- The basics of events and the event object.
- Common events like
click,input,change,submit, andDOMContentLoaded. - How to attach event listeners and use event properties.
To discover more events and their uses, refer to the MDN Event Reference.