How to make incremental and decremental Counter App using HTML, CSS & JavaScript
Faisal Jawed Khan
Posted on April 9, 2023
Hello developers, Welcome to my new blog. I recently deployed my first app on Netlify and am excited to share the project details. In this blog, I am going to explain how to create a counter app. Actually, if you are on a learning path then it’s very important to build different projects with your learning.
So without wasting any more time let's start the blog.
Prerequisites of this project:
If you read this blog then I am assuming that you know the basics of HTML, CSS and JavaScript.
It’s a javascript so I am not going to explain the html and css file.
Counter App:
As you can see, while doing this project I can split this into parts;
- Display to show the number
- Increment while pressing + button
- Decrement while pressing - button
- Reset the counter while pressing the button
Now it's time to start coding
01 Display to show the number
For this I can take the h2 tag under div.
<div class="updateNumberDiv">
<h2 class="updateNumber" id="updateNumber"></h2>
</div>
Select the id with document.getElementById of the h2 tag and assign a default value.
let score = 0;
let updateNumber = document.getElementById("updateNumber");
I can show the default number (0) with the help of textContent.
updateNumber.textContent = score;
Now it's time to show the increment, decrement and reset the default number.
I can solve this by taking one function for each increment, decrement and reset but it's too lenghty so I can use the querySelectorAll for selecting all buttons.
let updateBtn = document.querySelectorAll(".updateBtn button");
Then add click addEventListener on every button with the help of forEach loop. Then after that I can select the id of each button with the help of e.target.id.
Then I can use the if-else statement and after grabbing the id of the button, I can perform the increment, decrement and reset.
updateBtn.forEach((button) => {
button.addEventListener("click", (e) => {
let btnId = e.target.id;
if (btnId === "increment") {
score++;
updateScore();
return;
} else if (btnId === "decrement") {
score--;
updateScore();
return;
} else if (btnId === "reset") {
score = 0;
updateScore();
return;
}
})
})
Github Repository for this project:
https://github.com/faisaljawedkhan/counterApp/tree/dev
Counter App:
https://khancounterapp.netlify.app/
Conclusion
In this blog, we built a counter app.
If you think this will helpful for you the do Like, Comments, and Share with your colleagues and friends.
Do Follow me here on dev.to
Until then Happy Coding.
Posted on April 9, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 24, 2024