DEV Community

Stew
Stew

Posted on

JavaScript Counters Making a simple counter in javascript & HTML

Making a simple counter in javascript & HTML

This is my first post on here! In case of any confusion feel free to write me a comment and I'll try to update my post to be more clear!

Step 1 - HTML Setup

Starting with some simple HTML, an h1 for the display of the current count and Buttons for adding and subtracting

<h1 class="counter-display">(..)</h1>
<button class="counter-minus">-</button>
<button class="counter-plus">+</button>
Enter fullscreen mode Exit fullscreen mode

You can another tag for the counter display if you feel like. I'm just using a h1 for this example.


Step 2 - Adding Javascript

Selecting our DOM Elements

Firstly we'll start by select our various elements using document.queryselector and putting the result into some variables.

let counterDisplayElem = document.querySelector('.counter-display');
let counterMinusElem = document.querySelector('.counter-minus');
let counterPlusElem = document.querySelector('.counter-plus');
Enter fullscreen mode Exit fullscreen mode

Count Variable

Then we'll add a counter variable, so that we have a something to reference. I've decided to call this count.

let count = 0;
Enter fullscreen mode Exit fullscreen mode

This will be the variable that we'll be adding or subtracting from.

Adding Event listeners

We'll need to add eventlisteners to our elements so that we can dictate what happens when we click on our add or subtract buttons.

counterPlusElem.addEventListener("click",()=>{

});
Enter fullscreen mode Exit fullscreen mode

Here we have added an eventlistener to our counterPlusElem that listens after a click and then executes an anonymous function. This would be that same for our counterMinusElem counterMinusElem.addEventListener...

Functionality of our eventlisteners

Now, lets add the core functionality of adding to our counter.

counterPlusElem.addEventListener("click",()=>{
    counter++;
});
Enter fullscreen mode Exit fullscreen mode

Here we're taking our counter variable and adding 1 to it. You can achieve the same result by using counter = counter + 1

For our minus eventlistener we can use counter-- which is the same as counter++ but with subtracting instead of adding.

Updaing our display

To update our display we have 2 posibilities. We can either add our code directly to the eventlisteners like so.

counterPlusElem.addEventListener("click",()=>{
    counter++;
    counterDisplayElem.innerHTML = count;
});
Enter fullscreen mode Exit fullscreen mode

Selecting our counterdisplay element and setting it's innerHTML to be our count variable we just added 1 to.

But since both our plus and minus buttons should update our display we should make it into a function to avoid redundancy. Like so

function updateDisplay(){
    counterDisplayElem.innerHTML = count;
};
Enter fullscreen mode Exit fullscreen mode

I've decided to call my function updateDisplay as it's a function that updates our display

Now we're able to call our function updateDisplay. So our eventlistener would now look like this

counterPlusElem.addEventListener("click",()=>{
    counter++;
    updateDisplay();
});
Enter fullscreen mode Exit fullscreen mode

By having our new function we can call it at the start of the document. To have it updated when we load up the page. Right now it would just show (..) until we press one of our two buttons.

We should call it after we've defined our variables and elements. Like so.

let counterDisplayElem = document.querySelector('.counter-display');
let counterMinusElem = document.querySelector('.counter-minus');
let counterPlusElem = document.querySelector('.counter-plus');

let count = 0;

updateDisplay();
Enter fullscreen mode Exit fullscreen mode

Final code

Our final code should look like this if everything has been done correctly.

HTML

<h1 class="counter-display">(..)</h1>
<button class="counter-minus">-</button>
<button class="counter-plus">+</button>
Enter fullscreen mode Exit fullscreen mode

Javascript

let counterDisplayElem = document.querySelector('.counter-display');
let counterMinusElem = document.querySelector('.counter-minus');
let counterPlusElem = document.querySelector('.counter-plus');

let count = 0;

updateDisplay();

counterPlusElem.addEventListener("click",()=>{
    count++;
    updateDisplay();
}) ;

counterMinusElem.addEventListener("click",()=>{
    count--;
    updateDisplay();
});

function updateDisplay(){
    counterDisplayElem.innerHTML = count;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (6)

Collapse
 
nicklasspendler profile image
NicklasSpendler

Very good

Collapse
 
haond10adp profile image
Nguyễn Đức Hào

So whenever the count variable changes, we have to explicitly call updateDisplay() to update its presence in the DOM (counterDisplayElem.innerHTML). There's no way to detect variable change and update the DOM automatically.
I think what's called state in front-end frameworks is basically a thing that can change in the DOM. We need a variable to represent that thing so that when the variable changes, its presence in the DOM changes too, automatically.

In short, we just need a variable reflecting a thing that can change in the DOM.
If so, is this Svelte code snippet the perfect way of what we could declaratively code the counter example.

<script>
    let count = 0;

    function handleClick() {
        count += 1;
    }
</script>

<button on:click={handleClick}>
    Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
osinachiuro profile image
Osinachi

Hello Daniel,

Thanks for your post. I found it helpful in writing my code.

I am new to JavaScript.

I am trying to create a web page visitors counter that would increment on page load.
My counter is not incrementing and i can't figure out why.
I am using my localStorage to test before I move it to a database.
Any ideas?
Can i share my code with you?

Regards,
Osinachi

Collapse
 
chris69bryant profile image
chris69bryant

Just followed my way through your excellent example. I'm somewhat a newbie although been programming PLCs for years. I'm just getting into things in this sector. Thank you for the example, it has helped massively. God speed and keep up the good work.

Chris B.
Chester,
Cheshire.

Collapse
 
otongjr profile image
otongjr

Hello, my counter app buttons first increase the counting before doing the actual functionality it is supposed to do. What might have gone wrong??

Collapse
 
maniche1981 profile image
Maniche1981

Thanks a lot mate, great explanation