Creating a Simple Counter Using HTML/JavaScript
Trevor Vardeman
Posted on April 15, 2022
The Intro
I recently completed my first project at Flatiron School, which I'm very proud of! Feel free to read more about there here. During the review of my project, I was given a live coding task. The task was simple: to add a counter on the DOM that would add 1 to a number when a button was clicked.
Sounds easy, right? Especially after having completed a fairly large project. Well, unfortunately, it gave me a litle trouble. I knew what pieces of the solution were fairly quickly, but putting them together on-the-spot proved challenging.
After feeling just a little down with how I performed on this exercise, I realized how important it was to have been given such a task. While the task itself was simple, there was more to the challenge than meets the eye.
It was the first time I had to really explain my thought process out loud to someone that I didn't know, and it was also the first time I had to perform a coding task in front of someone I had never met before.
After graduating from Flatiron, I'm certainly going to have to code in front of people while explaining my thought process - it's going to happen in every programming interview. This was really my first foray into what that would potentially feel like, even though this task was far simpler than any job interview.
It was great practice, and practice makes perfect.
So, today, let's talk about the task I was given and how to solve it. Hopefully there's someone out there who will stumble across this post in a time of need!
The Task
Here were the deliverables:
- Add a button to the web page
- Add a counter on the page
- When the button is clicked, add 1 to the counter
I was allowed to hard-code the number 0 to begin the exercise.
The Pieces
So, how can we break this down in terms of steps we need to take to solve the problem? Here is how I broke it down:
- We need to create the button in HTML
- We also need to create a place for the counter in HTML
- We'll add an event listener to connect the JavaScript we're going to write to the HTML
- We will need a JS click event to trigger the counter
- When clicked, we'll update the counter
The HTML
In our index.html file, we'll start by doing the following, which is far more detail regarding the first 2 items above.
- Within our HTML's body, create a div to house everything
- Create a button
- Write some text to describe our number
- Create a span with an ID of "counter" so that we can store it as a variable in our index.js file
- Include our starting number of 0
NOTE: I'm not covering it here for simplicity, but in your HTML file, don't forget your boilerplate HTML and to point to your JavaScript file!
Here's what the HTML steps above look like:
<div>
<button type="button">Click Me!</button>
Number of Clicks: <span id="counter">0</span>
</div>
The JavaScript
Next we need to add the JavaScript portion. This consists of steps 2 - 6 in the "The Pieces" section above. In more detail, this is what we'll do:
- Create a variable for the HTML button
- Create a variable for the HTML counter
- Add an event listener to be able to track when the button is clicked, and then to use a callback function to...
- Add 1 to the existing number
First, we need to store a reference to the button from our HTML in JavaScript. I used querySelector
to find the button by its "type" attribute. Then I added an event listener to my button variable:
const button = document.querySelector("button")
Next, we need to store the counter as a variable so that we can increment it when it's clicked. Instead of using querySelector
, let's store this variable by using getElementById
:
const counter = document.getElementById("counter")
Next, I added an event listener to that button:
button.addEventListener("click", () => clickHandler())
When the button is clicked, I'm calling a callback function titled clickHandler
which will house the code that tells the program what action to take when the button is clicked. This is the part where I got tripped up in the live-coding exercise. I find that very often, I accidentally overcomplicate things.
The first thing I tried to do was take the number within the counter, using the innerHTML
property, and add 1 to it, which looked like this:
function clickHandler() {
counter.innerHTML + 1
console.log(counter)
}
The problem here is that the number that I'm trying to increment, 0, isn't actually an integer (number) at all. I found this out by using the typeof
operator:
console.log(typeof counter.innerHTML)
Turns out, that the number 0 I had added to HTML was actually a string. So when trying to add 1 to it, it wasn't working because the data types didn't match.
The solution is more elegant because it solves two problems at once. It will use the classic increment operator (++), and at the same time, will convert the string of "0" to an integer, alleviating our data inconsistency! The new function will look like this:
function clickHandler() {
counter.innerHTML++
}
Try it out for yourself!
While we're here, though, let's look at how we can simplify this just a little bit further.
The Refactor
We can refactor this 3 line function into a single-line arrow function:
const clickHandler = () => counter.innerHTML++
Excellent! This still works and trims our code while not making it any harder to read. But can we go even further?
Of course we can.
Remember the event listener we created that looked like this?
button.addEventListener("click", () => clickHandler())
Well, since we were able to shorten our function down to one line of code, we can just go ahead and execute the function's action directly within the event listener itself! Here's what it looks like when you edit the event listener to perform this action immediately:
button.addEventListener("click", () => counter.innerHTML++)
The Final Product
Now we've successfully created a functional counter button that our users can interact with on the DOM in about 10 lines of code including both HTML and JavaScript (minus the boilerplate)!
To recap what the final code looks like altogether, see below!
HTML body:
<body>
<div>
<button type="button">Click Me!</button>
Number of Clicks: <span id="counter">0</span>
</div>
<script src="./index.js"></script>
</body>
JavaScript:
const button = document.querySelector("button")
const counter = document.getElementById("counter")
button.addEventListener("click", () => counter.innerHTML++)
Gif Demonstration:
I hope you found this post helpful in your coding journey, feel free to reach out if you have any questions or comments. :)
-Trevor
Posted on April 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 2, 2024