Responding to the User: Events
Web pages feel alive when they react to you: buttons click, forms submit, keys are pressed. This reaction happens through events — signals the browser sends when something happens. In this chapter, you'll learn what events are, how to listen for them, and how to respond with your own code.
What Is an Event?
An event is a message from the browser that something occurred. Examples:
- The user clicks a button (
click) - The user presses a key (
keydown) - The user moves the mouse over an element (
mouseover) - The page finishes loading (
load)
You don't call events yourself — the browser fires them. Your job is to listen for the ones you care about and run code in response.
Listening for Events
An event listener is a function you attach to an element. When the event happens, the browser calls your function.
// HTML needed: <button id="hello">Say hi</button>
const button = document.querySelector('#hello');
function sayHi() {
console.log('Hi there!');
}
button.addEventListener('click', sayHi);addEventListener takes two things:
- The event name as a string, like
'click'. - The function to run when it fires. This function is often called a callback, because the browser "calls you back" when the event happens.
Arrow functions work well here when the handler is short:
button.addEventListener('click', () => console.log('Clicked!'));The Event Object
When an event fires, the browser passes an event object to your handler. It holds useful details, like which element was clicked or which key was pressed.
document.addEventListener('keydown', (event) => {
console.log(`You pressed: ${event.key}`);
});Try this in your browser console, click on the page, and press keys. Each press logs the key name.
A Practical Example: Updating the Page
Here we combine events with DOM changes (covered in the previous chapter). Each click updates a heading:
const button = document.querySelector('#counter');
const heading = document.querySelector('h1');
let clicks = 0;
button.addEventListener('click', () => {
clicks++;
heading.textContent = `Clicked ${clicks} times`;
});This is the heart of interactive web pages: listen for input, update the page, wait again.
Show diagram source
graph LR
U[User acts] --> B[Browser fires event]
B --> H[Your handler runs]
H --> P[Page updates]
P --> UCommon Mistakes
- Wrong event name.
'Click'with a capital C does nothing — names are lowercase. - Selecting before the element exists. Run your code after the element is on the page, or listen for
DOMContentLoaded. - Forgetting to attach. Defining a handler does nothing until you pass it to
addEventListener.
Exercise
What two arguments does addEventListener take?
Show answer
The event name as a string (like 'click') and the handler function to run when the event fires.
Exercise
How would you find out which key the user pressed?
Show answer
Add a keydown listener and read event.key inside the handler function.
Spotted a mistake, or code that does not work?