All subjects

PF 102 · BSIT

Event-Driven Programming

Prelims decks, midterm modules on the Socorro Mini Map, and now the pre-final: Enter the Building — double-click a building in your edp-lab island and step inside.

Fire → Listen → Handle — growing every session

  1. DAY 01

    Name the model: GUI, events, Fire → Listen → Handle

  2. DAY 02

    A real page that reacts to click, hover, and focus

  3. DAY 03

    GitHub history + a teaser of the 3D island

  4. DAY 04

    Enable STEP 0–7 on the Socorro Mini Map lab

  5. MIDTERM

    Customize the island — then live-demo it

  6. PRE-FINAL

    Enter the Building — one app, two modes, listeners that respect the mode

How to use this page

  1. 1

    Open each deck and step through it the same way we did in class.

  2. 2

    Say Fire → Listen → Handle out loud for every example before you look at the code.

  3. 3

    For midterm: customize the island, then prepare the Midterm 04 live demo (theme, events, colors).

  4. 4

    For pre-final: follow the 4 hands-on lessons in order. Save → refresh → test after every step.

Prelims coverage

From GUIs and the Fire → Listen → Handle model through your first handlers, Git workflow, and the Socorro Mini Map lab starter.

01

GUIs & the event model

Vocabulary and mental model — no project yet

Presentations from class

What you must be able to explain

  • What a GUI is, and why interactive pages need events
  • Sequential programs run line by line; event-driven programs wait for the next event
  • Fire → Listen → Handle: an event is raised, a listener detects it, a handler responds
  • JavaScript is event-driven from the start — browsers fire DOM events constantly
  • Three ways to attach a handler; addEventListener is the one to default to
  • The event object carries type, target, and other details into your handler
  • Every event has capturing (down) and bubbling (up) phases
script.jsrecommended pattern
const btn = document.getElementById('myBtn');

btn.addEventListener('click', function () {
  alert('Button was clicked!');
});

Lines worth memorising

Fire → Listen → Handle is the vocabulary for the rest of the term.

The next step depends on whichever event happens next — not the next line in a list.

addEventListener is preferred over inline onclick handlers.

02

Your first interactive page

Click, hover, focus — and read the event object

Presentations from class

What you must be able to explain

  • Build a project folder with index.html and script.js
  • Change text and styles inside a click handler
  • React to mouseover / mouseout and input focus
  • Read e.type and e.target from the event parameter
  • Stop a form submit (or link navigation) with preventDefault()
  • Put listeners on a parent and a child to watch bubbling in the console
script.jsclick + style change
const box = document.getElementById('box');

box.addEventListener('click', function () {
  box.textContent = 'Clicked!';
  box.style.backgroundColor = '#6366f1';
  box.style.color = 'white';
});
script.jspreventDefault
form.addEventListener('submit', function (e) {
  e.preventDefault();
  console.log('Form did not reload the page.');
});

Lines worth memorising

Your handler receives an event parameter — use it, do not ignore it.

preventDefault() stops the browser's built-in action without removing your handler.

03

Protect the work, preview the lab

Commit history + the same events on a bigger canvas

Presentations from class

What you must be able to explain

  • Initialize a repo, make a first commit, and push to GitHub
  • The edit → test → commit → push loop for every lab
  • The Socorro 3D map uses the same Fire → Listen → Handle pattern as your 2D page
  • Where the course is headed: from a button click to a mini 3D island

Lines worth memorising

If it works in the browser, protect it with a commit before you leave class.

2D lab and 3D map share one mental model — only the canvas changes.

04

Socorro Mini Map starter

Uncomment STEP 0 → 7; same EDP pattern in 3D

Presentations from class

What you must be able to explain

  • Clone the edp-lab starter and open index.html (needs internet for Three.js CDN)
  • scene.js builds the island; events.js holds handlers; main.js registers listeners
  • Enable steps in order: camera → paint/HUD → mousemove → click → resize → hover → keydown
  • Commit after each step that works — do not dump everything in one commit
  • Customization later: at least one new event and one visible color change
main.jssame pattern as Day 2
window.addEventListener('mousemove', onMouseMove);
canvas.addEventListener('click', onClick);
window.addEventListener('resize', onResize);
window.addEventListener('keydown', onKeyDown);

Lines worth memorising

Uncomment the full STEP block — half a step leaves the lab broken.

mousemove, click, resize, keydown — still Fire → Listen → Handle.

Midterm coverage

Continue edp-lab — do not restart a flat page. Bridge the pattern on the island, customize handlers, then submit the island checkpoint. Follow EXAMPLE-modification-walkthrough.md (live preview on this site — same file as your fork).

Student guide

EXAMPLE-modification-walkthrough.md

Worked example — uncomment surroundings helpers, wire click and R, enable B for night mode, test checklist, then customize colors and keys for your submission.

Open full guide

Stretch guide

EXAMPLE-add-building-walkthrough.md

Add buildings to the island with x/z coordinates, w/h/d sizes, and the on-screen map legend.

Open guide

Stretch guide

EXAMPLE-add-props-walkthrough.md

Trees, paths, and birds — same Mesh recipe as buildings, with optional motion in main.js.

Open guide

Stretch guide

EXAMPLE-add-sun-walkthrough.md

Visible sun by day, moon at night — sprites that follow the camera, swapped with B.

Open guide
M1

Midterm

Events & Listeners on the Socorro Mini Map

Continue edp-lab — prove STEP 0A–7 before customizing

Presentations from class

What you must be able to explain

  • Midterm continues your edp-lab fork — not a brand-new flat events-lab folder
  • Fire → Listen → Handle on the canvas: click → main.js listener → onClick → paint/HUD
  • File map: scene.js (read), events.js (handlers), main.js (listeners + animate loop)
  • Island events already in play: click, mousemove, resize, keydown, load
  • Baseline gate: select, hover, R reset, and resize must work with a clean console
main.js + events.jssame pattern as Day 4
// Listen (main.js)
canvas.addEventListener('click', onClick);

// Handle (events.js)
function onClick(event) {
  // raycast → paintBuilding → HUD
}

Lines worth memorising

Handlers without listeners do nothing. Listeners without handlers crash.

Master the island pattern first — customization is new reactions on the same loop.

M2

Midterm

Customize island events

EXAMPLE walkthrough → your own click, hover, and key behaviors

Presentations from class

What you must be able to explain

  • Modify behavior — do not rebuild Three.js
  • Follow EXAMPLE-modification-walkthrough.md: surroundings colors, R reset, B night mode
  • Optional: visible sun / moon sprites — EXAMPLE-add-sun-walkthrough.md (B swaps them)
  • Change click colors with paintBuilding / edpWater / edpIsland
  • Customize hover in updateHover; use keydown as the keyboard focus analogue
  • Pick 2+ ideas from the activity menu; new events need a listener in main.js
events.jsEXAMPLE click wiring
if (selected) {
  highlightSurroundings(selected);
} else {
  resetHud();
  resetSurroundings();
}
events.js · toggleNightModeB key · sun ↔ moon
if (nightMode) {
  edpSun.intensity = 0.35;
  edpSunSprite.visible = false;
  edpMoonSprite.visible = true;
} else {
  edpSun.intensity = 1.5;
  edpSunSprite.visible = true;
  edpMoonSprite.visible = false;
}

Lines worth memorising

Keep R working while you add new keys — graders will try it.

At least one new/changed event and one visible color change you can demo in 5 seconds.

M3

Midterm

Island checkpoint

Submit your fork · README · in-class demo

Presentations from class

What you must be able to explain

  • Deliverable: one GitHub edp-lab fork URL + in-class demo (Pages optional bonus)
  • Required: baseline works, new/changed event, visible color change, 2+ menu ideas
  • README must include a My Modifications section (event, file, what user sees)
  • Push 2+ meaningful commits — not one dump named final
  • Demo script: name the event, listener file, handler, and visible result

Lines worth memorising

Do not submit a broken base with pretty colors that never load.

Wire both sides: handler in events.js and addEventListener in main.js.

M4

Midterm

Live Island Demo Day

Next week — present your customized mini map to the class

Presentations from class

What you must be able to explain

  • Next week is a live demo — open your map, do not only talk about code
  • 3–5 minutes: theme + reason → island tour → trigger events → color choices → README
  • For every feature: Fire → Listen → Handle out loud (event, main.js, events.js, visible result)
  • Creativity counts: theme, layout, props/roads/sun, HUD voice — choices you can defend
  • Bring a filled event sheet; practice once with a timer before class
  • This demo uses the 50-point island rubric: points ÷ 50 × 100 = your demo % (this activity only)
spoken patternsay this for each feature
When the user does ____ (FIRE),
main.js listens with ____ (LISTEN),
events.js runs ____ (HANDLE),
and we see ____ on the island.

Lines worth memorising

Pretty without a working event is incomplete. Working without a theme is incomplete too.

Demo the EXAMPLE personalized — not a verbatim starter screenshot.

Biggest slices: event 24%, baseline 20%, visible customization 20%.

Pre-final · Enter the Building

Same edp-lab island. Double-click a building and you are inside it; press Esc and you are back. One app, two modes — and every handler checks mode before it acts.

Start here

Hands-on: Enter the Building — 4 lessons

Step-by-step with copyable code and checkboxes: the idea → wire the doors → who ate the Exit click → checkpoint.

Open lessons
P1

Pre-final

Enter the Building

Midterm made the island yours — now step inside it

Presentations from class

Hands-on steps

Play the finished demo, learn the event map, meet the mode flag.

Open lesson

What you must be able to explain

  • Pre-final continues your edp-lab fork — same island, one new interaction
  • One app, two modes: a mode variable says whether you are on the island or inside
  • Three event paths change the mode: dblclick a door, keydown Escape, click the Exit button
  • Handlers read mode first and decide if their job still makes sense (guard clause)
  • A double-click fires click, click, then dblclick
  • No second HTML page — entering must be handlers + a mode flag
the event mapmemorise this
dblclick building → canvas 'dblclick' → enterInterior(building) → mode = 'inside'
keydown Escape    → window 'keydown'  → exitInterior()          → mode = 'island'
click Exit button → #exit-btn 'click' → exitInterior()          → mode = 'island'

Lines worth memorising

The browser keeps firing every event. The handler decides if it still makes sense.

One app. Two modes. Listeners that respect the mode.

P2

Pre-final

Wire the Doors

Copy the boxes, type the events

Presentations from class

Hands-on steps

Ten small steps: provided parts → tag → room → enter → exit → look around.

Open lesson

What you must be able to explain

  • Tag a building with interior: 'key' and build its room with makeInterior (provided helper)
  • Rooms sit at x = ±400 — beyond the camera's 300-unit view range
  • enterInterior and exitInterior both start with a guard clause
  • Escape is checked before the mode guard in onKeyDown — it must work inside
  • The Exit button is a DOM listener: edpExitButton.addEventListener('click', onExitButtonClick)
  • animate() returns early while inside and calls lookAroundInterior instead of orbit + hover
events.jsguard first
function enterInterior(building) {
  if (mode !== 'island') return;
  const interior = edpInteriors[building.userData.interior];
  if (!interior) return;
  mode = 'inside';
  currentInterior = interior;
  edpCamera.position.copy(interior.eye);
  edpCamera.lookAt(interior.lookAt);
}

Lines worth memorising

Save → refresh → test after every step.

Pass the handler, don't call it: onExitButtonClick, not onExitButtonClick().

P3

Pre-final

Who Ate the Exit Click?

Break it on purpose, then explain the bubble

Presentations from class

Hands-on steps

Add the Event trace, move the click listener to window, watch it break, fix it.

Open lesson

What you must be able to explain

  • event.target is what you clicked; event.currentTarget is whose listener is running
  • Clicking Exit bubbles button → mode-bar → body → html → document → window
  • The canvas is a sibling of the button, not a parent — a canvas listener never hears it
  • The mode guard fails here because exitInterior already changed mode before the bubble arrived
  • Fix A: listen on the canvas · Fix B: check event.target · Fix C: stopPropagation (last resort)
  • preventDefault stops the browser's action; stopPropagation stops the climb to parents
Event trace · brokenlistener on window
click → onClick            target: exit-btn · listener on: window   · mode: island
click → onExitButtonClick  target: exit-btn · listener on: exit-btn · mode: inside

Lines worth memorising

The click wasn't eaten. It bubbled.

Fix where the listener lives before you stop propagation.

P4

Pre-final

Inside Checkpoint

A classmate enters and leaves — you explain every event

Presentations from class

Hands-on steps

Hard gates, README My Interiors, commits, demo script, paper drill.

Open lesson

What you must be able to explain

  • Deliverable: same edp-lab fork · README My Interiors · 3+ commits · live demo · paper drill
  • Hard gates: no second page · no re-enter inside · Exit doesn't trigger onClick · functions from memory
  • 50-point rubric — points go to events and state, not 3D art
  • Your own building must be enterable — renaming the demo Cafe doesn't count
spoken patternenter, Esc, and Exit button
When the user double-clicks the ____ (FIRE),
main.js listens with canvas 'dblclick' (LISTEN),
events.js runs enterInterior() (HANDLE),
and mode becomes 'inside' — see the badge (STATE).

Lines worth memorising

If a classmate can enter and leave without your help, the feature is real.

Cheat sheet

The patterns most likely to appear on the prelim exam.

Fire → Listen → Handle

01

Fire

Something raises an event — a click, a key, a resize, a page load.

02

Listen

An object waits with addEventListener for that specific event name.

03

Handle

Your function runs and updates the UI — text, color, HUD, camera.

Sequential vs event-driven

Sequential

  • Instructions run in a fixed order
  • The next step is the next line
  • The computer drives the program alone

Event-driven

  • Objects fire events; other objects react
  • The next step depends on the next event
  • A back-and-forth between user and computer

Attach a handler the recommended way

const btn = document.getElementById('myBtn');

btn.addEventListener('click', function (e) {
  console.log(e.type);   // "click"
  console.log(e.target); // the button element
});

Prefer addEventListener — it keeps HTML clean and lets you attach more than one handler to the same element.

Common events

CategoryEventWhat triggers it
MouseclickElement is clicked
MousemouseoverPointer enters an element
MousemouseoutPointer leaves an element
MousemousemovePointer moves (used for hover highlight on the island)
KeyboardkeydownA key is pressed
FormfocusAn input becomes selected
FormsubmitA form is submitted
WindowloadThe page finishes loading
WindowresizeThe browser window changes size

Bubbling vs capturing

Bubbling (default)

Handler runs on the target first, then walks up through parents. This is what you get with a normal addEventListener.

Capturing

Handler walks down from the top before the target. Enable it with { capture: true }.

EDP Lab — events on the island

Same pattern as the 2D page lab. Uncomment STEP 0 → 7 in order.

EventWhereWhat happens
mousemovewindowTrack pointer → hover highlight on buildings
clickcanvasSelect a building → color + HUD update
resizewindowKeep the 3D view correct when the window changes
loadwindowOptional camera nudge once on page load (STEP 0A)
keydownwindowKeyboard reset / control (STEP 7)
requestAnimationFrameloopDraw the scene each frame; optional orbit + hover

Pre-final — handlers that respect the mode

Same listeners as midterm. Each handler checks mode first.

HandlerOn the islandInside a building
onClickSelect + show the building nameName the prop you clicked
onDoubleClickEnter if it has a door, otherwise detailsDoes nothing
onKeyDownR reset · B night · Esc does nothingOnly Esc works → exitInterior()
animate()Orbit + hoverlookAroundInterior()
onMouseMoveRecords the mouseRecords the mouse (same)

event.target

The element the user actually clicked — the deepest one.

event.currentTarget

The element whose listener is running right now. Different from target? The event bubbled.

Check yourself

Answer out loud first, then reveal. If you can explain these without notes, you are ready.