That's the best way to solidify your learning! Let's put your new knowledge of the DOM, Functions, and Conditionals into practice with a classic beginner project: The Simple Counter.
🚀 Project Idea: Simple Counter
This project involves manipulating a number displayed on a webpage using buttons.
🎯 Goal
Create a simple web page with:
* A display area showing a starting number (e.g., 0).
* A Subtract button.
* An Add button.
The buttons should update the number shown on the screen.
🛠️ Step-by-Step Implementation
1. Setup the HTML (index.html)
Create the structure and give elements IDs so JavaScript can find them easily.
<!DOCTYPE html>
<html>
<head>
<title>Simple Counter</title>
</head>
<body>
<button id="subtract-btn">Subtract</button>
<h1 id="counter-display">0</h1>
<button id="add-btn">Add</button>
<script src="script.js"></script>
</body>
</html>
2. The JavaScript Logic (script.js)
You need to implement the following logic in your script.js file:
A. Initialize the State and Select Elements
// 1. Initialize a variable (the state)
let count = 0;
// 2. Select the elements using DOM methods
const display = document.querySelector('#counter-display');
const addButton = document.querySelector('#add-btn');
const subtractButton = document.querySelector('#subtract-btn');
B. Create the Core Functions
// Function to update the display (reusable!)
function updateDisplay() {
display.textContent = count;
}
// Function for adding
function increment() {
count++; // Arithmetic operator
updateDisplay();
}
// Function for subtracting
function decrement() {
count--; // Arithmetic operator
updateDisplay();
}
C. Handle the Events
// Attach the functions to the button clicks
addButton.addEventListener('click', increment);
subtractButton.addEventListener('click', decrement);
✨ Challenge: Add a Condition
To make it more fun, let's use a conditional! Modify the decrement function to prevent the counter from going below zero.
function decrement() {
// Use an 'if' statement to check the condition
if (count > 0) {
count--;
updateDisplay();
} else {
// Optional: show a message if the condition fails
console.log("Cannot go below zero!");
}
}
This project covers all the fundamentals we've discussed: Variables (let count), DOM Selection and Manipulation (querySelector, .textContent), Functions (increment, decrement), Operators (++, --), and Conditionals (if/else).
Give this a try! If you get stuck or want to move on, we can discuss Array Methods like map(), filter(), and reduce(), which are essential for processing data efficiently.
Would you like a brief overview of the most common Array Methods next?
0 Comments