Creating a Simple Counter Using HTML/JavaScript
Tags: webdev, beginners, javascript, programming
Published: 2022-04-15 05:42:24

### 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](https://dev.to/trevortx/first-project-worldwide-weather-4dno). 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:

1. We need to create the button in HTML
2. We also need to create a place for the counter in HTML
3. We'll add an event listener to connect the JavaScript we're going to write to the HTML
4. We will need a JS click event to trigger the counter
5. 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.
1. Within our HTML's body, create a div to house everything
2. Create a button
3. Write some text to describe our number
4. Create a span with an ID of "counter" so that we can store it as a variable in our index.js file
5. 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:
1. Create a variable for the HTML button
2. Create a variable for the HTML counter
3. Add an event listener to be able to track when the button is clicked, and then to use a callback function to...
4. 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`](https://developer.mozilla.org/en-US/docs/Web/API/Element/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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof) operator:

`console.log(typeof counter.innerHTML)`
![Image of console logging the typeof "counter.innerHTML" which returns "string"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8r0apkkjxaaxpzo2ja0b.png) 

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 (++)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment), 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:

![Gif of the working counter. When clicked, the counter increments by 1.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qjgi764si4ahspku0xtr.gif)

I hope you found this post helpful in your coding journey, feel free to reach out if you have any questions or comments. :)

-Trevor