JavaScript DOM Events
DOM events allow you to create interactive and responsive web applications by responding to user actions and other occurrences on the page.
1. Event Handling Basics
Event handling involves attaching event listeners to HTML elements. An event listener is a JavaScript function that “listens” for a specific event to occur and executes when that event is triggered.
<button id="myButton">Click Me<button>
// Get the button element
const button = document.getElementById("myButton");
// Attach an event listener for the "click" event
button.addEventListener("click", function() {
alert("Button clicked!");
});
2. Common DOM Events
Here are some commonly used DOM events. Also please see our lesson on Javascript Events to understand more events that could happen to an element:
click
: Occurs when an element is clicked.mouseover
: Occurs when the mouse pointer enters an element.mouseout
: Occurs when the mouse pointer leaves an element.keydown
: Occurs when a key is pressed down.keyup
: Occurs when a key is released.submit
: Occurs when a form is submitted.
3. Event Object
When an event occurs, an event object is created and passed to the event handler function. This object contains information about the event, such as the target element, event type, and more.
<button id="myButton">Click Me<button>
const eventButton = document.getElementById("eventButton");
eventButton.addEventListener("click", function(event) {
// Access the event object properties
console.log("Event type:", event.type);
console.log("Target element:", event.target);
});
Example two and better flexibility:
// Define a named function for the event handler
function handleButtonClick(event) {
// Access the event object properties
console.log("Event type:", event.type);
console.log("Target element:", event.target);
}
// Get the button element
const eventButton = document.getElementById("myButton");
// Attach the named function as an event listener
eventButton.addEventListener("click", handleButtonClick);
Example three:
// This works because the function is defined before it's used
const eventButton = document.getElementById("myButton");
// Attach the named function as an event listener
eventButton.addEventListener("click", handleButtonClick);
// Define the named function
function handleButtonClick(event) {
console.log("Button clicked!");
}
4. Preventing Default Behavior
Sometimes, you may want to prevent the default behavior of an event. For example, prevent a form from submitting or a link from navigating to a new page.
<a href="https://www.example.com" id="link">Click Me<a>
const link = document.getElementById("link");
link.addEventListener("click", function(event) {
// Prevent the default behavior
event.preventDefault();
alert("Link clicked, but default behavior prevented.");
});
5. Third Parameter of EventListener called useCapture
The third value in the addEventListener
method is an optional boolean parameter called useCapture
. This parameter determines whether the event should be captured during the capturing phase or during the bubbling phase of the event propagation.
In the DOM event flow, an event can be captured and processed in two phases:
- Capturing Phase / Event Capturing: The event is captured from the root of the DOM hierarchy down to the target element. Capturing is the first phase of event propagation. During this phase, the event starts from the root of the DOM hierarchy and travels down through the nested elements until it reaches the target element. Think of it as the event “capturing” its way down to the element that triggered it.
- Bubbling Phase / Event Bubbling: The event bubbles up from the target element to the root of the DOM hierarchy. Bubbling is the second phase of event propagation. After the event has been captured at the target element, it begins to “bubble” back up through the nested elements, from the target element to the root of the DOM hierarchy.
By default, the useCapture
parameter is set to false
, which means the event will be captured during the bubbling phase. If you set it to true
, the event will be captured during the capturing phase instead. Below is an example:
<div id="outer">
<button id="innerButton">Inner Button<button>
<div>
// Get the outer and inner elements
const outer = document.getElementById("outer");
const innerButton = document.getElementById("innerButton");
// Event listener with useCapture set to true
outer.addEventListener("click", function() {
console.log("Capturing phase: Outer div clicked");
}, true);
// Event listener without useCapture (default is false)
innerButton.addEventListener("click", function() {
console.log("Bubbling phase: Inner button clicked");
});
In the example above, clicking the “Click Me” text triggers the event handlers. The event follows this flow:
Capturing Phase:
- The event starts at the root (
<html>
element) and travels down to the outer<div>
element because of the capturing phase. - The capturing event handler attached to the outer
<div>
is triggered, logging “Capturing phase: Outer div clicked.”
Target Phase:
- The event reaches the target element, which is the inner
<div>
. - The bubbling event handler attached to the inner
<div>
is triggered, logging “Bubbling phase: Inner div clicked.”
Bubbling Phase:
- The event bubbles back up to the outer
<div>
because the event’s default behavior is to bubble during this phase. - No additional handlers are triggered during the bubbling phase in this example.
To summarize, capturing and bubbling phases describe how an event propagates through the DOM tree, either from the root down to the target (capturing) or from the target up to the root (bubbling). The useCapture
parameter in addEventListener
allows you to control whether an event is captured or bubbled. By default, events bubble during the bubbling phase.
This tutorial covers event handling basics, common DOM events, the event object, and preventing default behavior. You can experiment with different events and event handlers to create interactive and responsive web applications.