Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

How to build a counter application with JavaScript

amrin

Overview

We are going to build the Counter application with JavaScript.

Let's get started.

Prerequisites

  1. In this tutorial, knowledge of the fundamentals of HTML, CSS, and JavaScript is assumed. If you're new to web development, we recommend that you learn the fundamentals of these technologies first.
  2. Before starting, download the starter files from here.
  3. A preview of what we will be building is given below.

This project has will do the following:

  1. Display the result
  2. Decrement
  3. Increment
  4. Resetting the counter

These are all the features our Counter application will have. Let’s implement them one by one.

1. Display

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>

We’ll use the DOM to get the element in JavaScript.

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


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

The document.querySelector method takes a class, an ID, or the element's name.

We’ll 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, we'll add the Increment The Counter function.

2. Incrementing the counter

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


const incrementBtn = document.querySelector("#increment")

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);

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 include, as well as the eventHandlerFunction to handle the event.

 
 incrementBtn.addEventListener('click', increment);

As you can see, we've only added the name of the increment function. You can also declare the increment function there.

If we run the code right now, we’ll get an error because the increment function doesn’t exist yet.

Let’s create the increment function.


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

First, let's declare a variable to store the value. Then, inside the increment function, we'll increment the value by one. Lastly, we set the value as the text of the display. Otherwise, the display won’t update.

Note: It is neccessary to declare the value variable outside the function. If it is declared inside the increment function, it won’t work, because it will update on every click, setting the value to 1.

The increment button should now work properly.

Let’s move on and add the decrement function.

3. Decrement the counter

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


const decrementBtn = document.querySelector('#decrement');

Then we’ll add the event listener with .addEventListener.


decrementBtn.addEventListener('click', decrement);

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

This is almost like the increment function, but the difference is that we're not adding one, but subtracting one from the value. After that, we'll set the value as the display text.

4. Reset the counter

The reset functionality is the simplest one. After grabbing the reset button, we can add the event listener.


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

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

The reset button just sets the value to zero.

The Counter application is done! We can see the finished project below. Even though we have a lot of repeating code that goes against the DRY (Don't Repeat Yourself) principle. In the next section, we’ll show how to refactor the code to make it more clean and DRY.

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;
}

Refactoring the code

Even though our application is done, the code is not clean as it includes a lot of repetition. For example, we're adding the event listener multiple times, selecting the three buttons separately, and so on.

Let’s clean up the code a bit.

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

This way, we can remove a lot of code.

//refactored code
const allBtns = document.getElementById('#allBtns');

We can now add an event listener to the allBtns element, as follows:


allBtns.addEventListener('click', counter);

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

We can do this as follows:


function counter(e) {
	const btn = e.target;
  console.log(btn)
}

The event handler function takes an argument e, which is an object with a lot of properties.

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

https://i.ibb.co/bWXncnz/console-screenshot.pnghttps://i.ibb.co/bWXncnz/console-screenshot.png

We can check to see the ID name, and then add the specific function to the button.

We get an element’s ID with e.target.id.


const btn = e.target.id;

We 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;
  }
}

Here’s the code after we're done refactoring it:


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;
}

Now, the code is much cleaner and easier to understand.

Let's take a look at the full code below.

RELATED TAGS

javascript

CONTRIBUTOR

amrin
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring