DEV Community

Cover image for How to build a counter app with JavaScript
Amrin
Amrin

Posted on • Updated on

How to build a counter app with JavaScript

If you google What is the best way to learn programming? Everyone will say the best way to learn programming is by building projects.

But, you won’t find a complete guide that will show what and how to build projects.

To fill that gap, I started the JavaScript Project Series. In this series, I’ll show you how to build projects from small toy projects to portfolio-worthy projects.

This is part 1 and project 1. In this part, I’ll build a simple Counter app with Vanilla JavaScript.

So, without any delay let’s get started.

Prerequisites

This is a project tutorial so, I assume you have a basic knowledge of HTML, CSS, and JavaScript.

You don’t have to know all of it. Just the fundamentals.

If you think you need a little brush up on your JavaScript skills, don’t worry. I wrote an article on JavaScript Fundamental you can read it here.

Starter files

As I said before this is a JavaScript project series. So, I won’t show you how to write the HTML and CSS.

Before starting download the starter files and open them on your favorite code editor.

Starter Files

Breaking down the projects into smaller parts

You might be thinking why doesn't she start coding?

Bare with me. Breaking down projects will save you a ton of time when you start coding.

It’s one of the most important skills for programmers.

Even though today’s project is not that big, I’ll still show you how to break it down into little parts.

Because It’ll help you when you start building bigger projects on your own.

Let’s break down the project.

The first step of breaking down a project is understanding the project and what are the features it’ll have.

Counter App: The Counter App will have an increment, decrement, and reset button. And a display to show the number.

counter app

As you can see, when you understand the project you are building. It is automatically broken down into small parts.

So, the parts are:

  1. A display to show the number.
  2. Increment the counter,
  3. Decrement the counter,
  4. Reset the counter.

Now that you have the small parts, It’s finally the time to start coding.

Let’s roll your sleeves and start coding.

01. A display to show the number.

To create the display for the number first we need to get the element into the JavaScript file.

Here’s the display element in the HTML.


  <p class="counter-preview">0</p>


Enter fullscreen mode Exit fullscreen mode

We’ll use the DOM to get the element in JavaScript. If you don’t know much about DOM check out this article before moving on.

To get the element in JavaScript you can use the document.querySelector method like this:

const display = document.querySelector('.counter-preview');
Enter fullscreen mode Exit fullscreen mode

The document.querySelector method takes, a class or an ID or the elements name.

We’ll just leave it here, when we add the Increment, Decrement, and Reset Functionalities we’ll update the display.

Let’s add them one by one. First Increment The Counter function.

02. Increment the counter

Just like the display, to add the Increment functionality first you’ll have to get the incrementBtn into the JS file.

const incrementBtn = document.querySelector("#increment")
Enter fullscreen mode Exit fullscreen mode

After that, you’ll have to add the EventListener to the Button.

You can add an event to an element with element.addEventListener method. Like this:

 incrementBtn.addEventListener('EventName', eventHandlerFunction);
Enter fullscreen mode Exit fullscreen mode

The addEventListener method takes two arguments, the first one is the Event you want to add and the second one is the function that determines what will happen when the event occurs.

Let’s add the event you want to add and the event handler function to handle the event.

 incrementBtn.addEventListener('click', increment);
Enter fullscreen mode Exit fullscreen mode

As you can see I added just the name of the increment function. You can also declare the increment function there. It just looks cleaner this way.

If you run the code right now you’ll get an error. because the increment function dosen’t exist yet.

Let’s create the increment function.

let value = 0; 
function increment() {
  value += 1;
  display.textContent = value;
}
Enter fullscreen mode Exit fullscreen mode

First, declare a variable to store the value. And then inside the increment function, increment the value by one. Lastly, set the value as the text of the display, otherwise, the display won’t update.

Note: You have to declare the value variable outside the function. If you declare it inside the increment function it won’t work. Because it’ll update on every click, setting the value to 1.

Now the increment button should work properly.

Let’s move on and add the decrement function.

03. Decrement the counter

Just like the increment button first, you’ll have to grab the decrement button.

const decrementBtn = document.querySelector('#decrement');
Enter fullscreen mode Exit fullscreen mode

Then you’ll have to add the event listener with .addEventListener.

decrementBtn.addEventListener('click', decrement);

function decrement() {
  value -= 1;
  display.textContent = value;
}
Enter fullscreen mode Exit fullscreen mode

This is almost like the increment function, but the difference is you are not adding one you are subtracting one from the value. And then setting the value as the display text.

04. Reset the counter

The reset functionality is the simplest one. After grabbing the reset button, you add the evenListener.

const resetBtn = document.querySelector('#reset');
resetBtn.addEventListener('click', reset);

function reset() {
  value = 0;
  display.textContent = value;
}

Enter fullscreen mode Exit fullscreen mode

The reset button just sets the value to zero.

This is it. The counter app is done. You can see the finished project here. Even though we have a lot of repeating code that goes against the DRY(don’t repeat yourself) principle. Don’t worry in the next section I’ll show you how to refactor the code to make it more clean and DRY.

Here’s all the code:

const display = document.querySelector('.counter-preview');
const incrementBtn = document.querySelector('#increment');
const decrementBtn = document.querySelector('#decrement');
const resetBtn = document.querySelector('#reset');

incrementBtn.addEventListener('click', increment);
decrementBtn.addEventListener('click', decrement);
resetBtn.addEventListener('click', reset);

let value = 0;
function increment() {
  value += 1;
  display.textContent = value;
}

function decrement() {
  value -= 1;
  display.textContent = value;
}

function reset() {
  value = 0;
  display.textContent = value;
}
Enter fullscreen mode Exit fullscreen mode

Refactoring the code

Even though our app is done, the code is not clean. We are repeating a lot. For example, we are adding EventListener there times, and selecting the three buttons separately and so on.

Let’s clean up the code a bit.

You can start refactoring by selecting the parent of the button. If you add an EventListener to the parent the event will be added to the children too.

This way you can remove a lot of code.

//refactored code
const allBtns = document.getElementById('#allBtns');
Enter fullscreen mode Exit fullscreen mode

Now you can add an EventListener to allBtns element. Like this

allBtns.addEventListener('click', counter);
Enter fullscreen mode Exit fullscreen mode

Now you need to select all the buttons and perform the actions according to the button.

To do that you can do this.


function counter(e) {
    const btn = e.target;
  console.log(btn)
}
Enter fullscreen mode Exit fullscreen mode

The event handler function takes an argument e, it’s an object with a lot of properties.

If you call e.target you’ll get the currently clicked element which is a button in this case.

console-screenshot.png

Now you can check to see the id name, and then you can add the specific function to the button.

You get an element’s id with e.target.id

const btn = e.target.id;
Enter fullscreen mode Exit fullscreen mode

Now you can compare the currently clicked button with the class names and add the actions.

function counter(e) {
  const btn = e.target.id;
  if (btn === 'increment') {
    value += 1;
    display.textContent = value;
  } else if (btn === 'decrement') {
    value -= 1;
    display.textContent = value;
  } else {
    value = 0;
    display.textContent = value;
  }
}
Enter fullscreen mode Exit fullscreen mode

Here’s all the code after refactoring:

const display = document.querySelector('.counter-preview');
const allBtns = document.querySelector('#allBtns');

allBtns.addEventListener('click', counter);

let value = 0;
function counter(e) {
  const btn = e.target.id;
  if (btn === 'increment') {
    value += 1;
  } else if (btn === 'decrement') {
    value -= 1;
  } else {
    value = 0;
  }

    display.textContent = value;
}
Enter fullscreen mode Exit fullscreen mode

The code is much cleaner and easy to understand.

Finished project

source code

Conclusion

In this article, we built a counter app.

If this was helpful follow me on twitter @coderarmin for more articles like this.

Until then Happy Coding

Discussion (0)