JavaScript Intermediate: Data, the DOM and Events
Events: Responding to Users
In this lesson you will
- Attach a listener with addEventListener
- Use the event object and preventDefault
- Handle many elements with event delegation
Introduction
A page that never reacts is just a poster. Events are signals from the browser: "the user clicked", "a key was pressed", "the form was submitted". You write code that listens for those signals and responds.
The simple explanation
An event listener is a function that runs when something happens.
addEventListener(type, function) says: "when this event happens on this element, call this function." Press Run, then click the button inside the result.
Quick quiz
What do you pass to addEventListener?
The event object
The function receives an event object with details about what happened. event.target is the element that was clicked.
Common events
click: a mouse click or tap.input: the value of a field changes as the user types.submit: a form is submitted.keydown: a key is pressed.mouseover: the pointer moves onto an element.
Forms and preventDefault
Submitting a form normally reloads the page. event.preventDefault() stops that, so JavaScript can handle the data instead.
Quick quiz
What does event.preventDefault() do on a form submit?
Event delegation
If you have 100 list items that each need a click handler, you do not need 100 listeners. Put one listener on the parent. Events bubble up from the item to its parents, and event.target tells you which item was clicked.
Delegation also works for items you add later.
Try it yourself
Build a counter. Add a button that increases a number shown in a paragraph each time it is clicked. Hint: keep the count in a variable.
Summary
addEventListener("click", fn)runsfnwhen the event happens.- The event object has details such as
target. preventDefault()stops default actions like form submission.- Event delegation uses one parent listener for many children.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading