🎮 10 Even More JavaScript DOM Games — Learn by Building (Vanilla JS)
Get code https://github.com/lsvekis/10-JavaScript-DOM-Coding-Games-Learn-by-Building-Fun-Mini-Projects/
Miss the joy of learning JavaScript by making tiny interactive things? This sequel brings 10 new DOM mini-games (Exercises 21–30) you can run by simply opening an index.html
. They’re built with vanilla JavaScript, HTML, and a dash of CSS—no build step, no frameworks. Each card includes a short description, minimal UI, and a Run All Tests bar for quick sanity checks.
This volume focuses on: precise event handling, animation loops, time-based logic, drag & drop, DOM state transitions, and lightweight architecture that scales.
What’s Inside (Exercises 21–30)
21) Stopwatch & Laps
Goal: Start/stop a millisecond timer, capture laps, reset cleanly.
Core APIs: setInterval
, performance.now()
, enabling/disabling controls, DOM list updates.
How it works:
- Buttons are wired with
addEventListener
and a simpleenable()
utility togglesdisabled
. tick()
computes elapsed time asaccumulated + (now - base)
and renderstoFixed(3)
.- Laps are appended as
<li>
nodes to an ordered list.
Learning outcomes: debouncing controls, measuring time deltas reliably, rendering at ~30 FPS without jank.
22) Hot/Cold Finder
Goal: Find a hidden point in a box using proximity hints (“Cold/Warm/Hot”).
Core APIs: mouse events, rectangle math (getBoundingClientRect()
), Euclidean distance.
How it works:
- A random target
[x, y]
is chosen inside the arena. - On
mousemove
, we compute the cursor’s local point and display a hint based onMath.hypot(dx, dy)
. - On
click
, if close enough, mark the round as “Found!”.
Learning outcomes: mapping page coordinates → local container coordinates; simple geometry for UX.
23) Skip Count Target
Goal: Reach an exact target by adding/subtracting a random step size.
Core APIs: text updates, button events, simple arithmetic state machine.
How it works:
- A new round picks a step from
[2,3,4,5,7]
and a target between 15–55. +
and–
mutatenow
, and the UI reports Exact, Overshoot, or Below.
Learning outcomes: communicating state transitions clearly via minimal DOM text updates.
24) Lights Out (3×3)
Goal: Toggle cells to switch off all lights; each click toggles the cell + its neighbors.
Core APIs: grid generation, 2D indexing, neighbor toggling.
How it works:
- Cells are created once; each node stores
data-on
("1"
or"0"
). - On click, we compute
(x, y)
and toggle[self, up, down, left, right]
. - A “You win!” check uses
every(c => c.dataset.on === '0')
.
Learning outcomes: compact modeling (data attributes), side-effects on adjacent nodes, win detection.
25) Reaction Boxes
Goal: In 10 seconds, click only the red boxes; wrong clicks lose points.
Core APIs: periodic rounds (setInterval
), per-cell styling, scoring logic.
How it works:
- A 5×5 grid is built once; each second, three random cells are colored red.
- Clicks compare the clicked cell’s color; correct → green, wrong → muted slate; score updates instantly.
Learning outcomes: separating round scheduling from click handling, keeping UI honest with state.
26) Word Typer
Goal: Type the displayed word; incorrect letter resets your input.
Core APIs: input events, string prefix checks, timers.
How it works:
- On start, a 15s timer counts down;
input
comparesvalue
vscur
. - If
!cur.startsWith(value)
, we clear the input. If equal, increment score and rotate the word.
Learning outcomes: resilient input validation and quick feedback loops.
27) Sortable List (Drag & Drop)
Goal: Drag items to sort them alphabetically, then click Check.
Core APIs: HTML5 Drag & Drop (dragstart
, dragover
, drop
), DOM reordering.
How it works:
- We store the dragged text via
dataTransfer
. - On
drop
, we compute indices and reinsert the node usinginsertBefore()
accordingly. - Check compares current DOM order to the alphabetized array.
Learning outcomes: safe DOM reordering patterns, minimal DnD without dependencies.
28) Balloon Pop (Fixed & Smooth)
Goal: Balloons float upward—pop as many as you can in 12 seconds.
Core APIs: requestAnimationFrame
, time delta physics, steady spawning, pointer events, DOM recycling.
What changed (and why it’s solid now):
- Uses a persistent DOM (no
innerHTML = ''
each frame), so clicks don’t get lost. - Movement uses time-based motion (
dt = (ts - lastTs)/1000
) for stable speed across devices. - Spawning is cadenced (every ~350ms) instead of random per frame, ensuring a consistent flow.
- Balloons are cleaned up in place (when popped or offscreen), preventing memory leaks.
Learning outcomes: real-time loops with rAF
, predictable spawning, safe element lifecycle.
29) Countdown Math
Goal: Solve fast addition/subtraction problems for 20 seconds.
Core APIs: gated inputs, setInterval
countdown, small problem generator.
How it works:
- A round produces
a op b
, enables input, and awaits OK. - Correct answers increment score and produce a new problem; out of time disables controls.
Learning outcomes: micro-game loop with form controls and scoring.
30) Aim Trainer Grid
Goal: Hit the highlighted cell; maintain streaks before time runs out.
Core APIs: grid creation, “active” index, timed randomization.
How it works:
- A 5×5 grid is built once; every second, a random active index is highlighted.
- Clicks compare
i === active
to update Hits and Streak.
Learning outcomes: tight feedback, quick state flips, pacing via timers.
Architecture Notes
- Helpers: tiny
$()
and$$()
selectors,rand(n)
, andwait(ms)
keep code clear. - One-time DOM builds: grids/lists are created once; rounds only update styles/data, not the structure.
- State machines: each game keeps local state (
running
,timeLeft
,score
, etc.) for predictable flows. - Test bar: a minimal runner simulates clicks/inputs to verify that events are wired and core logic responds.
Key Techniques You’ll Practice
- Timekeeping with
performance.now()
andsetInterval
- Animation with
requestAnimationFrame
+ time deltas - Mouse & keyboard events, pointer events on touch devices
- Drag & Drop reordering without libraries
- Grid layout generation and neighbor logic
- Clean element lifecycle (create → update → remove)
How to Use These Games
- Save or clone the project and open
index.html
in your browser. - Play any card—each one is self-contained.
- Click Run All Tests to sanity-check your wiring.
- Tweak rules, styles, and difficulty to make each mechanic your own.
Extend the Challenges
- Stopwatch: add split averages and best lap highlighting.
- Hot/Cold: show a mini radar dot when you’re close.
- Lights Out: change board size (5×5) and auto-generate solvable states.
- Reaction Boxes: scale difficulty by time, count of red boxes, or penalties.
- Balloon Pop: spawn color tiers with different speeds/scores; add gentle sway (
x
sinusoid). - Aim Trainer: record reaction time per hit and chart streaks.
Final Thoughts
These compact projects turn DOM APIs into tangible skills—you’ll read coordinates, reason about time, move pixels, and ship tiny features with confidence. Because everything’s vanilla JS, you can lift ideas straight into any codebase or classroom.
