Events

An event is something that happens on a page — a click, a key press, a form being submitted. addEventListener lets your code wait for one of these and react when it actually happens, instead of running everything the instant the page loads. Every example below is live — try interacting with the result panel.

Listening for a click

The pattern is always the same: select an element, then tell it what to do when an event fires:

Try it yourself
Result

The input event

input fires every time the value of a text field changes — as the user types, not just once they're done:

Try it yourself
Result

The submit event

Forms fire a submit event when a user submits them — hitting Enter in a field, or clicking a submit button. Left alone, the browser then reloads the page to send the data off; calling event.preventDefault() stops that so you can handle the data with JavaScript instead:

Try it yourself
Result

The event object

Every listener receives an event object describing what happened. event.target is the exact element the event happened on — handy when one listener is watching several elements at once instead of attaching a separate listener to each:

Try it yourself
Result
Note: the parameter passed into a listener is often named event or e — that's just convention, not a keyword. It's a regular parameter, and the browser fills it in automatically when the event fires.