NEBians
search Sign In Register

Make It Interactive

Lesson 3 of 3 Coding game schedule25 min

Loading simulation…

sports_esportsPlay with the blocks and run your code

flagWhat you'll discover

  • arrow_forwardFind page elements with document.getElementById
  • arrow_forwardReact to clicks using addEventListener
  • arrow_forwardChange text and styles from inside event code
  • arrow_forwardKeep state with a counter variable across clicks

The DOM: your page as objects

When the browser loads HTML it builds the DOM — the Document Object Model — a live structure where every tag becomes an object JavaScript can grab and change. document.getElementById("magic-btn") fetches the element whose id is magic-btn; then msg.textContent = "Hi!" rewrites its text instantly, no reload needed. Every like-button animation, every chat message appearing, every dark-mode toggle you have ever seen is JavaScript editing the DOM exactly like this.

Events: giving your page ears

Pages sit still until something happens: a click, a key press, a finger scroll. These are events, and addEventListener lets your code listen for them: btn.addEventListener("click", function () { ... }) means "when this button is clicked, run this code". The function you hand over is called a callback — it waits patiently and fires every time the event occurs. This style is event-driven programming, and it is how every interactive interface on Earth is wired together.

Remembering with state

How does a page count clicks? With a variable declared OUTSIDE the event function: let clicks = 0. Each click runs clicks++ and writes the new number into the page. Because the variable lives outside, it survives between clicks — programmers call this state. Get the placement wrong (declare it inside the callback) and it resets to zero every click, stuck forever at 1. From game scores to shopping carts, managing state is one of the central challenges of real app development.

quizCheck your knowledge

1. What does addEventListener("click", myFunction) do?
2. Which line changes the words inside an element?
3. For a click counter, where must let clicks = 0 go?