Loading lessons...
Project 1: Interactive Counter
Project 1: Interactive Counter
Build a counter with buttons that increase and decrease a number.
Step 1: The HTML
<h1 id="count">0</h1>
<button id="addBtn">+1</button>
<button id="subBtn">-1</button>
Step 2: The JavaScript
let count = 0;
const display = document.getElementById("count");
document.getElementById("addBtn").addEventListener("click", function() {
count++;
display.textContent = count;
});
document.getElementById("subBtn").addEventListener("click", function() {
count--;
display.textContent = count;
});
Step 3: How it works
getElementByIdgrabs the elements.addEventListener("click", ...)reacts to clicks.textContentupdates the visible number.
Step 4: Try it
Click the buttons. The number changes each time. Congratulations, you made a working app!
Bonus ideas
- Add a reset button that sets count to 0.
- Prevent the count from going below 0.
- Change the color when the count is negative.
TL;DR
- Grab elements with getElementById.
- Listen for clicks with addEventListener.
- Update the page with textContent.
- Build small interactive features step by step.