In JavaScript, events are actions or occurrences that happen in the browser, which your code can respond to. They enable interaction between users and your webpage.
What Are Events?
Events can be triggered by user actions like clicks, key presses, mouse movements, or by the browser itself (e.g., loading a page).
Common Event Types
- click: User clicks an element
- keydown: User presses a key
- mouseover: Mouse pointer moves over an element
- submit: Form submission
- load: Page or image finishes loading
How to Listen to Events
You use addEventListener to attach a function (event handler) that runs when the event occurs.
📌 Deep Dive: Adding a Click Event Listener
const button = document.querySelector('button');
button.addEventListener('click', () => {
alert('Button clicked!');
});
Event Object
Event handlers receive an event object with details about the event, such as which key was pressed or mouse position.
📌 Deep Dive: Using the Event Object
document.addEventListener('keydown', (event) => {
console.log('Key pressed:', event.key);
});
Event Propagation: Capturing and Bubbling
Events propagate through the DOM in two phases:
- Capturing phase: Event moves from the document root down to the target element.
- Bubbling phase: Event bubbles up from the target element to the document root.
By default, listeners catch events during the bubbling phase, but you can listen during capturing by passing { capture: true } as an option.

💡 Event Propagation
Understanding event propagation helps you control which elements respond first and prevent unwanted side effects.
Removing Event Listeners
Use removeEventListener to detach an event handler. This requires a named function reference.
📌 Deep Dive: Removing an Event Listener
function onClick() {
alert('Clicked!');
}
button.addEventListener('click', onClick);
// Later, to remove the listener:
button.removeEventListener('click', onClick);
HTML Event Attributes vs. addEventListener
| Method | Description |
|---|---|
HTML attribute (e.g., onclick) | Inline, mixes HTML & JS, limited flexibility |
| addEventListener | Preferred, allows multiple listeners, better separation |
⚠️ Avoid Inline Event Handlers
Using inline event attributes like onclick is outdated and harder to maintain. Prefer addEventListener.
Summary
- Events are how JavaScript responds to user and browser actions.
- Use
addEventListenerto attach event handlers. - The event object provides useful information about the event.
- Understand event propagation (capturing and bubbling).
- Remove event listeners with
removeEventListenerwhen needed.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which method is preferred for attaching multiple event handlers to the same element?
Question 2 of 2
What does the event object provide to an event handler?
Loading results...