Skip to the content.

Lesson 6: Add Interactivity with JavaScript

Course home Previous: Lesson 5 Next: Lesson 7

Time: about 75 minutes.

Goals

By the end of this lesson you will be able to:

Concepts

JavaScript you need to read

const habits = [];                      // an array (a list), starts empty

const habit = {                         // an object: named values
  id: "a1",
  name: "Read",
  createdAt: "2026-12-01",
  done: ["2026-12-01"],                 // days it was ticked
};

function isDoneOn(habit, day) {         // a function: input -> output
  return habit.done.includes(day);
}

form.addEventListener("submit", (event) => {   // run this when the form is submitted
  event.preventDefault();                       // stop the page reloading
  // ...
});

The DOM

The DOM is the browser’s live model of your HTML. JavaScript can find elements (document.querySelector("#habit-list")), create them (document.createElement("li")), change their text (el.textContent = "Read") and listen for events (el.addEventListener("click", ...)).

Pure logic vs page code

habits.js (pure logic) app.js (page code)
Takes data in, returns new data Reads the form, listens for clicks, draws the list
No document, no window, no localStorage Calls the pure functions
Easy to test with Node (Lesson 9) Tested by hand in the browser
Example: toggleDay(habit, day) returns a new habit Example: when a checkbox changes, call toggleDay, then redraw

This split is the single most valuable design choice in the project. Write it into AGENTS.md if you have not.

Why textContent, not innerHTML

name.textContent = habit.name;   // safe: shows the text as text
name.innerHTML = habit.name;     // dangerous: treats the text as HTML

If someone names a habit <img src=x onerror=alert(1)>, innerHTML creates an image element and runs the script. textContent just shows those characters. AI agents often reach for innerHTML with template strings because it is short. Do not accept it for user-supplied text. More in Lesson 11.

Dates as day keys

The app stores days as text like "2026-12-01". Text keys are easy to compare, sort and save. Day maths (yesterday, last seven days) is done in UTC to avoid daylight saving surprises. You will test this in Lesson 9.

Walkthrough

Work in small steps and commit after each. Start a fresh agent session.

Step 1: The pure logic first

Read AGENTS.md and index.html. Create habits.js as an ES module with pure
functions only (no DOM, no storage):
- todayKey(date = new Date()) returns the local date as "YYYY-MM-DD"
- normalizeName(name) trims and collapses spaces
- validateName(name, habits) returns { ok: true, name } or
  { ok: false, error } for empty, longer than 60 characters, or a
  case-insensitive duplicate
- createHabit(name, { id, today }) returns { id, name, createdAt, done: [] }
- toggleDay(habit, dayKey) returns a NEW habit with that day added or
  removed; done stays sorted with no duplicates; never mutate the input
- removeHabit(habits, id) returns a new array without that habit
Show me the plan in a few bullets, then write it. Explain each function in
one sentence afterwards.

Review: are there any document or localStorage references? (There should be none.) Does toggleDay return a new object instead of changing the old one? Commit:

git add habits.js
git commit -m "Add pure habit functions"

Step 2: Add habits on the page

Create app.js as an ES module that imports from habits.js, and load it from
index.html with <script type="module" src="app.js"></script> in the head.
On form submit: prevent the reload, validate the name, show the error in
#form-error if invalid (and set aria-invalid on the input), otherwise add
the habit to an in-memory array, clear the input, keep focus in it, and
redraw the list. Hide #empty-state when there are habits.
Build each list item with createElement and textContent only, never
innerHTML. Use crypto.randomUUID() for ids with a simple fallback.
Plan first.

Test in the browser (python3 -m http.server 8000):

Commit.

Step 3: Tick habits for today

Each habit item needs a checkbox, inside a label with the habit name, that
shows whether the habit is done today. Changing it calls toggleDay for
today's key, replaces that habit in the array, and redraws. Keep the
checkbox keyboard accessible.

Test with mouse and with Space key on a focused checkbox. Commit.

Step 4: Delete with confirmation

Add a Delete button to each habit (type="button"). Clicking it asks
confirm('Delete "<name>" and its history?'). If confirmed, remove the
habit with removeHabit and redraw. Give the button an aria-label that
includes the habit name, so screen reader users know which habit it
deletes.

Commit.

Step 5: Streaks and the seven-day strip

Remember the streak decision from Lesson 4.

Add to habits.js:
- addDays(dayKey, n) using UTC date maths so daylight saving never skips
  a day
- currentStreak(habit, today): consecutive ticked days ending today, or
  ending yesterday if today is not ticked yet
- lastNDays(today, count) returning day keys oldest first
- completionRate(habit, today, windowDays = 7) as a whole percent
Then in app.js, under each habit show "Streak: N days · Last 7 days: P%"
(with "1 day" singular) and a row of seven small boxes for the last seven
days, marked done or not, each with a title showing the date and status.
Plan first.

Test by ticking today: streak shows 1. To test longer streaks without waiting a week, you will write tests in Lesson 9. For now, trust but verify: ask the agent to explain currentStreak line by line.

Commit.

Step 6: Compare with the reference

Open project/habits.js and project/app.js. Compare:

What good output looks like

Checklist

Mini-quiz

  1. Why does the submit handler call event.preventDefault()?
  2. What is wrong with item.innerHTML = "<span>" + habit.name + "</span>"?
  3. Why should toggleDay return a new habit rather than changing the one passed in?
  4. Why keep habits.js free of document?
  5. With today’s key 2026-12-05, a habit is ticked on 12-03 and 12-04 but not 12-05. What streak does the reference app show, and why?
Answers 1. Without it the browser submits the form the old-fashioned way and reloads the page, losing the in-memory list. 2. The habit name is inserted as HTML, so a name containing markup or a script-triggering attribute would run in the page (XSS). Use `createElement` and `textContent`. 3. Not mutating inputs makes the code predictable and easy to test: the old value stays valid, and bugs from shared changing state are avoided. 4. So the logic can run and be tested in Node without a browser, and stays reusable. 5. 2. Today is not ticked yet, so the streak counts back from yesterday (12-04, 12-03).

Assignment

  1. Add a “rename” feature: double-click or a Rename button turns the name into an input; Enter saves, Escape cancels. Reuse validateName so duplicates are still blocked (hint: let it ignore the habit being renamed). Plan first.
  2. Add the longest-ever streak (“Best: N days”). Put the function in habits.js.
  3. Commit each feature separately.

Next: Lesson 7: Save data with localStorage