Event listeners are functions in JavaScript that wait for and respond to user interactions or other events on web page elements.

💡 What is an Event Listener?
It's a way to "listen" for certain events (like clicks, key presses, or mouse movements) on elements and run code when those events occur.
Basic Syntax
Use addEventListener to attach an event listener to an element.
📌 Deep Dive: Adding a Click Listener
const button = document.querySelector('button');
button.addEventListener('click', () => {
alert('Button clicked!');
});
Common Event Types
click— User clicks an elementmouseover— Mouse pointer moves over an elementkeydown— A key is pressed on the keyboardsubmit— A form is submittedinput— User input changes in a form field
| Method | Description |
|---|---|
| addEventListener | Adds multiple listeners of the same type without overwriting |
| on[event] | E.g., element.onclick, can only assign one listener (overwrites previous) |
Removing Event Listeners
To remove, you need to use a named function reference:
📌 Deep Dive: Removing a Listener
const btn = document.querySelector('button');
function handleClick() {
console.log('Clicked!');
}
btn.addEventListener('click', handleClick);
// Later, to remove:
btn.removeEventListener('click', handleClick);
⚠️ Important
Anonymous functions cannot be removed because removeEventListener requires the exact same function reference.
Event Object
Event listeners receive an event object with details about the event.
📌 Deep Dive: Using the Event Object
document.addEventListener('keydown', event => {
console.log('Key pressed:', event.key);
});
💡 Event Propagation
Events bubble from child elements up to parent elements unless propagation is stopped using event.stopPropagation().
Summary
- Use
addEventListener(event, handler)to respond to events. - Always use named functions when you need to remove listeners later.
- The event object provides useful info about the event.
- Different events trigger on different user interactions.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which method allows adding multiple event listeners without overwriting existing ones?
Question 2 of 2
Why can't you remove an event listener added with an anonymous function?
Loading results...