Web pages are static until the user interacts with them. Event handling is the mechanism by which JavaScript listens for and responds to user actions (like a mouse click, key press, or form submission) or browser actions (like the page loading). This chapter is the key to creating truly interactive applications.
What is an Event?
An event is a signal that something has happened. Events are generated by the browser, and JavaScript lets you register functions that should be executed when a specific event occurs on a specific element. These functions are called event handlers or listeners.
Attaching Event Listeners
The standard and most flexible way to handle events is using the addEventListener()
method.
JavaScript
element.addEventListener(event, handlerFunction, useCapture);
event
: A string specifying the event type (e.g., 'click'
, 'mouseover'
, 'submit'
).
handlerFunction
: The function to run when the event occurs.
useCapture
(optional): A boolean to control the event flow (defaults to false
, which is bubbling).
JavaScript
const myButton = document.getElementById('submit-button');
// Define the function (the handler)function handleClick() {
alert('Button was clicked!');
myButton.textContent = 'Clicked!';
}
// Attach the listener
myButton.addEventListener('click', handleClick);
// You can also use an anonymous (inline) arrow functionconst header = document.querySelector('h1');
header.addEventListener('mouseover', () => {
header.style.color = 'red';
});
The Event Object
When an event occurs, the browser automatically passes an Event Object to the handler function. This object contains crucial information about the event itself.
JavaScript
myButton.addEventListener('click', (event) => {
// 'event' (or often 'e') is the event object
console.log('The element that fired the event:', event.target);
console.log('The mouse X coordinate:', event.clientX);
});
Essential Event Methods
Two methods on the Event Object are vital for controlling browser default behavior:
event.preventDefault()
: Stops the default action of an element.
event.stopPropagation()
: Stops the event from propagating (bubbling up) to parent elements.
JavaScript
const myLink = document.getElementById('my-link');
myLink.addEventListener('click', (e) => {
e.preventDefault(); // Stop the link from navigating
console.log('Link clicked, but navigation blocked!');
});
Common Event Types
Category | Event Type | Description |
Mouse | click | When the user clicks the element. |
| mouseover | When the pointer moves onto the element. |
| mouseout | When the pointer moves off the element. |
Keyboard | keydown | When a key is pressed down. |
| keyup | When a key is released. |
Form | submit | When a form is submitted. |
| input | When the value of an <input> or <textarea> element changes. |
Document | DOMContentLoaded | Fired when the initial HTML document has been completely loaded and parsed (best place to attach listeners). |
Export to Sheets
Event Bubbling (The Default Flow)
Events typically "bubble up" from the target element to its parents. If you click a paragraph, the click event also "happens" on the parent <div>
, then the <body>
, and so on, up to the document
. This behavior is the basis for Event Delegation (a technique where you attach a single listener to a parent to handle events on all its children, even those added dynamically).