Week 5: Events & Interaction
To Do This Week:
Assignments:
- Clickable Page (5%) is due this week — no AI-generated code (Due 9/30)
Finish and refine your Clickable Page. Make sure your numbered logic steps are commented at the top of your <script> tag.
Read (Optional!): Chapters from Eloquent JavaScript:
- Handling Events
- The Document Object Model (review)
Upcoming Assignments
- Slider/Menu Site (5%) (Due Week 7 — 10/7)
Module Notes
Last week we learned to select elements and change them. This week is about the middle of that loop: events — the moments a user (or the browser) does something, and the code we run in response.
An event is a message. A click, a keypress, a mouse moving, a page finishing loading, a form being submitted — each one is the browser saying "this just happened." Your job is to listen for the ones you care about and respond.
The pattern is always the same three parts:
target.addEventListener("eventType", handlerFunction);
// ↑ what to watch ↑ what happened ↑ what to do about it
In-class Exercise:
Event Playground: Clicks, Keys, Hovers & the Event Object- listen for different event types
- read the
eventobject - use
event.target - keyboard interaction
- event delegation (one listener for many elements)
preventDefault()
1. addEventListener — a closer look
This is the modern, preferred way to respond to events. You can attach many listeners to the same element, and it keeps your JavaScript separate from your HTML.
-
element.addEventListener("click", handler)
Runshandlerevery time the event fires. -
element.removeEventListener("click", handler)
Stops listening. (The handler must be a named function to remove it.)
The handler can be written inline or as a named function. A named function is easier to read, reuse, and debug:
// inline (anonymous) function
button.addEventListener("click", function () {
console.log("clicked");
});
// named function — same result, cleaner
function handleClick() {
console.log("clicked");
}
button.addEventListener("click", handleClick);
Watch out: write handleClick, not handleClick(). With the parentheses you call the function immediately and hand its result to the listener. Without them, you hand over the function itself, to be called later when the event fires.
2. Common Event Types
Mouse events
"click"// a full press-and-release on an element"dblclick"// double-click"mousedown"/"mouseup"// the press and the release, separately"mouseenter"/"mouseleave"// pointer enters or leaves an element"mousemove"// fires constantly as the pointer moves — use with care
Keyboard events
"keydown"// a key is pressed down (fires repeatedly if held)"keyup"// a key is released
Form & input events
"input"// fires on every change to a text field (great for live updates)"change"// fires when a field loses focus after changing (good for checkboxes, selects)"submit"// a form is submitted (usually paired withpreventDefault())"focus"/"blur"// a field gains or loses focus
Window & document events
"DOMContentLoaded"// the HTML is fully parsed — safe to select elements"load"// everything (images, etc.) has finished loading"scroll"// the user scrolls"resize"// the window changes size
3. The Event Object
When an event fires, the browser hands your function an event object full of details about what just happened. Catch it by naming a parameter — e or event by convention.
button.addEventListener("click", function (e) {
console.log(e); // the whole event object — explore it in the Console
console.log(e.type); // "click"
console.log(e.target); // the exact element that was clicked
});
Useful properties:
-
e.target
The element the event actually happened on. Essential for delegation (section 5). -
e.currentTarget
The element the listener is attached to (not always the same as target). -
e.type
The name of the event, e.g."click". -
e.key
For keyboard events — which key, e.g."Enter","a","ArrowLeft". -
e.clientX/e.clientY
For mouse events — the pointer's coordinates on screen.
// Demo: which key did the user press?
document.addEventListener("keydown", function (e) {
console.log("You pressed:", e.key);
if (e.key === "Enter") {
console.log("Enter was pressed!");
}
});
4. preventDefault()
Some elements have built-in browser behavior: a form reloads the page when submitted, a link navigates away. e.preventDefault() stops that default so your JavaScript can take over instead.
// Demo: handle a form without the page reloading
const form = document.getElementById("myForm");
form.addEventListener("submit", function (e) {
e.preventDefault(); // stop the page reload
const value = document.getElementById("name").value;
console.log("Submitted name:", value);
});
5. Event Delegation
Imagine 20 buttons, or a list where new items keep getting added. Attaching a listener to each one is tedious — and brand-new elements won't have listeners at all.
Event delegation solves this with one idea: events bubble up. A click on a child also registers on its parent. So you put a single listener on the parent, then use e.target to find out which child was actually clicked.
// One listener on the container handles all current AND future buttons.
const list = document.getElementById("list");
list.addEventListener("click", function (e) {
// did the click land on a button?
if (e.target.tagName === "BUTTON") {
console.log("You clicked:", e.target.textContent);
e.target.remove(); // for example, delete that item
}
});
Why this matters: a To-Do list, a photo gallery, a card grid — anything where items appear and disappear — is far cleaner with delegation than with a listener per item.
6. Running Code After the Page Loads
If your <script> runs before the elements exist, your selections return null. Two fixes:
- Put the
<script>at the bottom of the body (simplest). - Or wrap your code so it waits:
document.addEventListener("DOMContentLoaded", function () {
// safe to select and wire up elements here
});
Debugging Events in the Console
Events are invisible until you make them speak. The Console is how you confirm an event fired and see what it carried.
console.log("handler ran")// did my listener fire at all?console.log(e.target)// what element triggered it?console.log(e.key)// which key was pressed?console.dir(e)// expand the full event object to explore its properties
Common bugs to watch for:
- Passing
handler()instead ofhandlertoaddEventListener. - Listening on an element that is
nullbecause it wasn't selected correctly. - Wiring up listeners before the HTML exists (script too high on the page).
- Expecting
e.targetto be the container when it's actually the child that was clicked. - Forgetting
e.preventDefault()on a form and watching the page reload.
Workshop (Thursday)
We'll keep building fluency by working from logic steps and debugging together. Come with either your Clickable Page (to extend with richer interaction) or an experiment from the Event Playground.
- Start from plain-English logic steps, then translate one step at a time.
- Use Google and documentation (MDN, W3Schools) to look up specific syntax.
- Use AI to explain a specific event, property, or bug — not to generate whole solutions.
- Keep the Console open the entire time. Confirm each listener fires before moving on.
Try extending your Clickable Page with:
- A keyboard shortcut (
keydown+e.key) that triggers one of your changes. - A hover effect driven by
mouseenter/mouseleave. - A list where clicking an item removes it — using event delegation.
- A live text field that updates the page on every
input.