addEventListener: the core pattern
This is the pattern you'll use constantly: select an element, then tell it "when this event happens, run this function." Nothing runs until the event actually occurs.
Common events
| Event | Fires when |
|---|---|
click | An element is clicked |
input | A text field's value changes, as the user types |
submit | A form is submitted |
keydown | Any key is pressed |
mouseover | The mouse moves over an element |
The event object
The function passed to addEventListener automatically receives an event object with details about what happened. event.target is the exact element the event fired on โ extremely useful when the same function handles multiple elements.
Working with forms
event.preventDefault() is almost always the first line in a form's submit handler. Without it, the browser does its old-fashioned default behavior โ reloading the whole page โ which erases any JavaScript state you had.
See it live
This is a real, working form handled entirely by JavaScript โ try it:
Simple form validation
This combines Lesson 2's if statement with what you've learned about forms โ a real validation check before you'd actually send data anywhere.
Try it yourself
submit event listener that calls preventDefault(), grabs the input's value, and logs it. Confirm the page doesn't reload when you submit.
Level up: live character counter
<p> below it. Using the input event, update the paragraph to show how many characters have been typed, live, as the user types โ no submit button needed.
1. What does event.preventDefault() do on a form submit?
2. Which event fires as a user types into a text field?
3. What does event.target refer to?
addEventListener is how your code reacts to what a user does. event.target tells you exactly what triggered it, and preventDefault() stops a form's default page-reload behavior so your JavaScript can handle it instead.