Episode 9 of 18
Events
Listen for and respond to DOM events — attach event listeners to elements and handle clicks, mouse movements, and more.
Events
Events make web pages interactive. When a user clicks a button, types in an input, or scrolls the page, the browser fires an event. You can listen for these events and run JavaScript code in response.
addEventListener
var button = document.querySelector('button');
button.addEventListener('click', function() {
console.log('Button was clicked!');
});
addEventListener takes two arguments: the event type (string) and a callback function that runs when the event fires.
The Event Object
button.addEventListener('click', function(e) {
console.log(e); // The event object
console.log(e.type); // "click"
console.log(e.target); // The element that was clicked
console.log(e.target.textContent); // Button text
console.log(e.clientX); // Mouse X position
console.log(e.clientY); // Mouse Y position
});
The event object (e) contains details about the event — what element triggered it, mouse coordinates, which key was pressed, and more.
Common Event Types
| Event | Fires When |
|---|---|
click | Element is clicked |
dblclick | Element is double-clicked |
mouseover | Mouse enters the element |
mouseout | Mouse leaves the element |
keydown | A key is pressed down |
keyup | A key is released |
submit | A form is submitted |
focus | An input gains focus |
blur | An input loses focus |
scroll | The page or element is scrolled |
Removing an Event Listener
function handleClick(e) {
console.log('Clicked!', e.target);
}
button.addEventListener('click', handleClick);
button.removeEventListener('click', handleClick);
To remove a listener, you must pass the same function reference. Anonymous functions cannot be removed because there is no reference to pass.
Multiple Listeners
var items = document.querySelectorAll('li');
items.forEach(function(item) {
item.addEventListener('click', function(e) {
console.log('Clicked:', e.target.textContent);
});
});
Key Takeaways
addEventListener(type, callback)attaches an event listener to an element- The callback receives an event object with details about the event
e.targetis the element that triggered the event- Use
removeEventListenerwith a named function to detach listeners