DOM events are actions or occurrences that happen in the browser, which JavaScript can respond to. They enable interactivity on web pages by allowing scripts to react to user actions or browser changes.
💡 What Are DOM Events?
Events represent user interactions like clicks, typing, or page loading, and system occurrences such as timers or network responses.
Here are some of the most common DOM events you will use frequently:
| Event | Description |
|---|---|
click | Triggered when an element is clicked. |
mouseover | Occurs when the mouse pointer moves over an element. |
mouseout | Occurs when the mouse pointer leaves an element. |
keydown | Fires when a key is pressed down. |
keyup | Fires when a key is released. |
input | Occurs when the value of an input element changes. |
submit | Triggered when a form is submitted. |
load | Fires when the whole page or an image finishes loading. |
resize | Occurs when the browser window is resized. |
scroll | Fires when the user scrolls the page or an element. |
These events are attached to DOM elements using addEventListener, which allows you to specify the event type and the function to run when it occurs.
📌 Deep Dive: Adding a Click Event Listener
const button = document.querySelector('button');
button.addEventListener('click', () => {
alert('Button clicked!');
});
Note: Event listeners can be added to any element, and multiple listeners for different events can coexist on the same element.
💡 Event Object
Event handlers receive an event object containing details like the event type, target element, and mouse coordinates. This allows more precise control within the handler.
📌 Deep Dive: Using the Event Object
document.addEventListener('click', event => {
console.log('Clicked element:', event.target.tagName);
console.log('Mouse X:', event.clientX, 'Mouse Y:', event.clientY);
});
Mouse X: 150 Mouse Y: 300
⚠️ Avoid Inline Event Handlers
Do not use HTML attributes like onclick for event handling. Instead, use addEventListener to separate HTML and JavaScript cleanly and enable multiple listeners.
Other common events to explore as you build interactive pages:
change— when an input or select element's value changes and loses focus.focusandblur— when an element gains or loses keyboard focus.dblclick— when an element is double-clicked.
💡 Event Propagation
Events propagate through three phases: capturing, target, and bubbling. By default, listeners react during bubbling phase, which means events bubble up from the target element to ancestors.
Understanding common DOM events and how to listen to them is essential for creating responsive and dynamic user experiences.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which method is recommended to add event listeners to a DOM element?
Question 2 of 2
What does the event object provide inside an event handler?
Loading results...
