Lesson 4
Events & the event object
Build a practical mental model for events & the event object and use it in working JavaScript.
By the end, you will be able to…
- Explain events & the event object in your own words
- Use events & the event object in a small program
- Recognize and debug a common failure mode
Build the mental model
addEventListener attaches a callback that runs when a named event fires; the callback receives an event object describing what happened, including event.target — the exact element the event originated from.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
Nearly every interactive feature starts with an event listener; reading event.target correctly is what lets one listener handle many elements.
Real-world example
A shopping cart's 'remove item' buttons all sharing one listener that reads event.target to know which item was clicked.
Common mistakes
- Confusing event.target (where the event started) with event.currentTarget (where the listener is attached)
- Forgetting to call event.preventDefault() on a form submit, causing an unwanted page reload
- Attaching a new listener every render instead of once, causing duplicate handlers
Try it yourself
Challenge
Given a simulated event object, write handleClick that returns the clicked element's id.
Knowledge check
What does event.target represent?
Summary
addEventListener wires a callback to a DOM event; event.target tells you exactly what triggered it.