Pages that react: dynamic web pages
A static page looks the same every time. A dynamic page changes when the user acts. An action is called an event, for example a click on a button or a key being pressed. The code that runs for an event is the handler, and we attach it with a line such as button.onclick = () => { ... }. A page that counts clicks keeps the number in a variable, count. Each click runs count = count + 1 and then writes the new value into the page, so after three clicks the page shows 3. To read what the user typed into an input box, use its value: box.value holds the text, so "Hello " + box.value shows Hello Mona if Mona was typed. If the page does not do what you expect, debug: read any error message, read the code line by line, change one thing, and test again. In the buggy example the page stays empty because JavaScript is case-sensitive: textcontent is not the same as textContent, so the assignment creates a new, useless property and the visible text never changes.
1let count = 0; 2const show = document.getElementById("count"); 3document.getElementById("plus").onclick = () => { 4 count = count + 1; 5 show.textContent = count; 6};
| Click | count | Text on the page |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
1const box = document.getElementById("name"); 2document.getElementById("hello").onclick = () => { 3 document.getElementById("out").textContent = "Hello " + box.value; 4};
1const show = document.getElementById("count"); 2let count = 0; 3document.getElementById("plus").onclick = () => { 4 count = count + 1; 5 show.textcontent = count; 6};
On paper, trace the click counter for five clicks and write the text on the page after each. Then change the handler so that each click adds 2, and write the new table. Finally write the debugging routine in four short steps.