The Event Object: What It Is and Why It Matters
You'll learn what the event object is and why it's automatically passed to your event handler functions.
What Is the Event Object?
Every time an event occurs in the browser—a click, a keypress, a mouse movement—the browser creates a detailed event object that captures everything about what just happened. This object is automatically passed as the first parameter to your event handler function.
Think of the event object like a detailed incident report: when something happens in your application, this report tells you what happened, where it happened, which element was involved, and other crucial context.
Why It Matters
Without the event object, your event handlers would be blind. You'd know something happened, but not the specifics. The event object gives you access to:
- What element triggered the event (
target) - What element the listener is attached to (
currentTarget) - Event-specific details (mouse coordinates, which key was pressed, form values)
- Methods to control behavior (
preventDefault(),stopPropagation())
How You Use It
button.addEventListener('click', function(event) {
// 'event' is the event object - you can name it anything
console.log(event.type); // "click"
console.log(event.target); // the clicked element
console.log(event.timeStamp); // when it happened
});
// Common naming: 'e', 'evt', or 'event'
input.addEventListener('keydown', function(e) {
console.log('Key pressed:', e.key);
});
The event object is passed automatically—you just need to accept it as a parameter. Different event types provide different properties, but all share common core properties.
Key Takeaway: The event object is an automatically-created package of information about an event that gets passed to your handler functions, giving you essential details about what happened and tools to control event behavior.