JavaScript DOM Events
The DOM also supports events. Events are notifications that are sent by the browser when something happens in a document. Some of the most common events are:
- Click: Triggered when an element is clicked.
- Mouseover: Fired when the mouse pointer enters an element.
- Mouseout: Fired when the mouse pointer leaves an element.
- Keydown: Triggered when a key on the keyboard is pressed.
- Keyup: Fired when a key is released.
- Submit: Fired when a form is submitted.
- Change: Triggered when the value of an input element changes.
Event Handling
Event handling in JavaScript involves defining what should happen when an event occurs. You can use the addEventListener
method to attach event handlers to elements.
let element = document.getElementById("myElement");
element.addEventListener("click", function() {
console.log("Element clicked!");
});
This code attaches a click event handler to an element with the ID “myElement.” When the element is clicked, the function is executed, and “Element clicked!” is logged to the console.
Event Bubbling
Event bubbling is a propagation mechanism in the DOM where an event starts from the target element and bubbles up to the root of the document. It allows multiple event handlers to be executed, starting from the target element and moving up the DOM tree.
document.body.addEventListener("click", function() {
console.log("Body clicked!");
});
element.addEventListener("click", function() {
console.log("Element clicked!");
});
In this example, when the element is clicked, both the “Element clicked!” and “Body clicked!” messages will be logged to the console. This is due to event bubbling.
Event Capturing
Event capturing is the opposite of event bubbling. It allows you to capture events as they propagate down the DOM tree, starting from the root and moving towards the target element.
document.body.addEventListener("click", function() {
console.log("Body clicked!");
}, true);
element.addEventListener("click", function() {
console.log("Element clicked!");
}, true);
By setting the third argument of addEventListener
to true
, you enable event capturing. In this case, when the element is clicked, both the “Body clicked!” and “Element clicked!” messages will be logged to the console.
Task
Continuing the tribute page example, create an on-click event listener to open the link in the anchor tag a on a new tab.
JavaScript DOM Summary
Here is a summary of the JavaScript DOM that was covered in this chapter:
- The DOM is a programming interface that allows JavaScript to interact with HTML and XML documents.
- The DOM represents an HTML or XML document as a tree of objects.
- There are a number of methods that can be used to work with the DOM in JavaScript.
- The DOM also supports events, which are notifications that are sent by the browser when something happens in a document.