Module 19: Browser Interactions
Events
🏠The everyday picture
A doorbell. Nothing happens until someone presses it; then it rings. You decide in advance what happens when it's pressed.
📘What it really is
-
An event is something that happens on the page: a click, a key press, typing in a field, a form being sent, the page finishing loading.
-
addEventListenerconnects an event to a function (the handler):
const button = document.querySelector("#menu-button");
button.addEventListener("click", () => {
document.querySelector("nav").classList.toggle("open");
});
- Common events:
click: a click or a tap;input: the value of a field changes (every key press);change: a field is changed and left (useful for drop-downs and checkboxes);submit: a form is being sent;-
keydown: a key is pressed. -
The handler receives an event object with details, often named
eventore:event.targetis the element that was clicked or typed in. -
Avoid the old
onclick="..."attribute in HTML. Keep JavaScript in.jsfiles, like CSS in.cssfiles.
🖱️Try it
Build a menu button for phones:
- Add
<button id="menu-button" type="button" aria-expanded="false">Menu</button>to your header. - In CSS, hide the nav on small screens unless it has the class
open, and hide the button on large screens. - In
main.js, toggle the classopenon the nav when the button is clicked, and setaria-expandedto"true"or"false"to match (screen readers use it to announce whether the menu is open).
✅Quick check
Which event fires every time someone types a letter in a field?
Show the answer
input.
Why set aria-expanded on a menu button?
Show the answer
It tells screen-reader users whether the menu is open or closed.
