The counter
Section 3: JavaScript: the actionsLesson 3.3 · ⏱ 8 min
HTML
<h1 id="num">0</h1>
<button id="plus">➕</button>
CSS
body { font-family: Tahoma; text-align: center; }
h1 { font-size: 80px; }
button { font-size: 30px; padding: 10px 30px; }
JavaScript
let count = 0;
const plus = document.getElementById("plus");
plus.onclick = function () {
count = count + 1;
document.getElementById("num").textContent = count;
};
🖥️ The page in Robo Web:

📌 Note
count + 1 is a number, but count + "1" is text that sticks on: 0, then 01, then 011!📌 Another example: a counter with two buttons
One button adds, the other takes away, and both write the number.
HTML
<h1 id="num">0</h1>
<button id="minus">➖</button>
<button id="plus">➕</button>
CSS
body { font-family: Tahoma, sans-serif; }
body { text-align: center; }
h1 { font-size: 70px; }
button { font-size: 20px; padding: 8px 20px; }
JavaScript
let count = 0;
const num = document.getElementById("num");
document.getElementById("plus").onclick = function () {
count = count + 1;
num.textContent = count;
};
document.getElementById("minus").onclick = function () {
count = count - 1;
num.textContent = count;
};
🖥️ The page in Robo Web:

✍️ Practise
The counter.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
✍️ Practise
Fix it: 0111 instead of 3.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
A button that adds 5 to the counter every time.
👀 Show the solution🙈 Hide the solution
HTML
<h1 id="num">0</h1>
<button id="plus">+5</button>
CSS
body { font-family: Tahoma, sans-serif; }
button { font-size: 20px; padding: 8px 20px; }
JavaScript
let count = 0;
document.getElementById("plus").onclick = function () {
count = count + 5;
document.getElementById("num").textContent = count;
};
🖥️ The page in Robo Web:

Result: 3 clicks: 15
Medium
Add a “Reset” button that takes the counter back to 0.
👀 Show the solution🙈 Hide the solution
HTML
<h1 id="num">0</h1>
<button id="plus">➕</button>
<button id="reset">Reset</button>
CSS
body { font-family: Tahoma, sans-serif; }
button { font-size: 20px; padding: 8px 20px; }
JavaScript
let count = 0;
const num = document.getElementById("num");
document.getElementById("plus").onclick = function () {
count++;
num.textContent = count;
};
document.getElementById("reset").onclick = function () {
count = 0;
num.textContent = count;
};
🖥️ The page in Robo Web:

Result: back to 0.
Hard
A counter that doubles the number: 1, 2, 4, 8...
👀 Show the solution🙈 Hide the solution
HTML
<h1 id="num">1</h1>
<button id="dbl">×2</button>
CSS
body { font-family: Tahoma, sans-serif; }
button { font-size: 20px; padding: 8px 20px; }
JavaScript
let count = 1;
document.getElementById("dbl").onclick = function () {
count = count * 2;
document.getElementById("num").textContent = count;
};
🖥️ The page in Robo Web:

Result: 4 clicks: 16

