Coding Newbie

javascript simple counter

Create a Simple Counter using JavaScript

Creating your own numbers counter using JavaScript is a simple project, that will help you understand the basics of JavaScript mechanism. In addition, you can use the code for later, as a part of more complex projects. This step-by-step guide will help you with that.

If you are not already familiar, you should know some basic CSS and JavaScript. My advise is to go through this lessons first:

If you already understand these subjects, we can continue and create our won simple counter.

First, we will create the structure, or the HTML part.

HTML

When it comes to HTML part of our code, we need few elements:

  • a counter, which we will store as paragraph
  • two buttons, one for increasing the number, the other for decreasing

In order to have better control in CSS, we will organize those elements as parts of separate divisions (div).

<div class="container"> <!--- Container with all our elements -->
    <div class="counterSection"> <!--- The section where our counter will be -->
         <p id="counter">0</p> <!--- THE COUNTER -->
    </div>
    <div class="btnSection"> <!--- The section with our buttons -->
        <button id="decBtn">-</button> <!--- DECREASING BUTTON -->
        <button id="incBtn">+</button> <!--- INCREASING BUTTON -->
    </div>
</div>

If you load HTML file, our Counter would look like this:

plain html simple counter

A plain HTML document. Now, we can make it a slight better with CSS.

CSS

We use the CSS file of our code to make our page (or counter in this case) to design it and make it more appealing.

If you are interested to read more about CSS, please feel free to read a post What is CSS and why is CSS so important?

Personally, my first step when writing CSS project is to set some default settings. These settings refer to:

  • Restarting margins and paddings to 0 for all elements by using universal character * . This neat little trick excludes any potential differences in margin or padding that may occur throughout our code.
  • Give all our elements box-sizing: border box; property, which will make margins part of our element’s width and height. This allows us to have more effective control over the size of the elements.
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

Now, when the stage is set, we can move on to writing the actual styling.

Next step will be to set the width of our entire counter, by setting the width and height of the .container class div element. Also, let’s add some background color:

.container {
    width: 300px;
    height: 300px;
    background-color: rgb(160, 252, 255);
}
simple counter css part 1

Ok, we have width and color, but our elements just do not look good. First of all, they are pushed to the left corner. We want them to be in the center of our container.

To achieve this, we will use display: flex property. This is extremely useful way to position and set the behavior of elements within the parent element, in our case the container div. So, we add few lines of code, which will center them:

.container {
    width: 300px;
    height: 300px;
    background-color: rgb(160, 252, 255);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

And now the result is much better:

simple counter css part 2

We have our buttons and counter centered. Let’s make them a slightly bigger:

#counter {
    font-size: 150px; /* setting the font size of our counter */
}

.btnSection button {
    font-size: 20px; /* setting the font size of our buttons */
    width: 30px;     /* their width and height */
    height: 30px;
}

We used px as units in this project. If you are interested to learn what are other available sizing units, please read CSS Units Quick Guide: PX vs EM vs REM.

Feel free to experiment with CSS design.

We now have simple and clean look of our counter:

simple counter css final

In the end, pressing the buttons for increasing or decreasing the value will do nothing, because we did not added a functionality to our buttons. To achieve this, we must use JavaScript. To get familiar with the use of JavaScript and the basic of this language, you are more then welcome to read the article What is JavaScript? Complete Beginners Guide.

JavaScript

First step is to connect our HTML elements with JavaScript code. We will achieve this by storing them into separate variables.

To learn about variables, and different variable alternatives, feel free to read posts:

VAR and LET: All You Must Know About JavaScript Variables

Introducing CONST: New JavaScript Declaration

const counter = document.getElementById('counter');
const decrease = document.getElementById('decBtn');
const increase = document.getElementById('incBtn');

We have stored our counter, decrease and increase button as three separate variables: counter, decrease, increase.

To achieve this, we use the JavaScript command document.getElementById(‘idname’). This command targets the specified id, and stores that element as a variable, or a const in this case.

Next thing we need, is to declare a variable that will do the counting. This will actually be our counter, so we will give it a abbreviation of the name:

let cnt = 0;

Finally, we get to the point where we will set our buttons and make them functional.

To achieve this, we use the command addEventListener. This command makes our code “listen” to events, such as clicks, mouse scroll, submit, etc.

So, in our little project, we wish to check whether we have clicked on some button. Let’s start with decrease button.

decrease.addEventListener('click', function(){ // listen for click on decrease button, and start the function when clicked
    cnt--; // reduce cnt by one
    counter.innerText = cnt; // set cnt value to our counter element
});

As described in comments above, our code works as following:

  • check for click event for decrease, which is the button with an id desBtn.
  • if clicked, the function starts
  • it reduces the value of cnt, which is the actual counting
  • takes that value and stores it with innerText command into counter variable, which is the HTML element (a paragraph in this case) with id counter.

Now, if you try to click on “minus” button, you should see the value of your counter decreasing.

For counting up, the code is quite similar. It just needs to add a value by one, and again place it in the paragraph.

decrease.addEventListener('click', function(){
    cnt++; // increases cnt by one
    counter.innerText = cnt;
});

JavaScript End Code

const counter = document.getElementById('counter');
const decrease = document.getElementById('decBtn');
const increase = document.getElementById('incBtn');

let cnt = 0;

decrease.addEventListener('click', function(){
    cnt--;
    counter.innerText = cnt;
});

increase.addEventListener('click', function(){
    cnt++;
    counter.innerText = cnt;
});

Conclusion

And there you have it, simple and functioning numbers counter.

Feel free to upgrade it and play around with style.

Also, you can try adding a reset button, which returns the counter value back to zero. If you understand the logic behind eventListener and innerText, it should not be a difficult task.

Leave a Comment

Your email address will not be published.

%d bloggers like this: