Week 5: Events & Interaction

To Do This Week:

Assignments:

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:

Upcoming Assignments


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

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.

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

Keyboard events

Form & input events

Window & document events


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:

// 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:

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.

Common bugs to watch for:


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.

Try extending your Clickable Page with:


Reference Links