How To Create A JS Counter

How To Create A JS Counter

Hello, my web dev friends.

Today I'll be showing you how to create a counter using Javascript(JS). As a beginner learning JS, it is essential that you know how to do this as it will help to build up a powerful JS developer or Front End Engineer.

Now the first thing we need to do is to add some markup. I'm assuming you already know how to link your files. This code below is just the HTML part.

// This is my index.html 
<html> 
<body>
<div class = "card">
<h1>JS Counter</h1>
<p class = "counter">0</p>
<div class = "buttons">
<button class="btn btn-next">Increment</button>
<button class="btn btn-prev">Decrease</button>
</div>
</div>
</body>
</html>

Screenshot 2022-10-13 at 13-52-49 A Pen by Kelison.png Alright. The image above shows you the output you should get after typing in all that. That should be all for the markup, all that's left now is the CSS and JS which is really simple. Now I'll head on to the CSS.

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body,html {
            background-color: rgb(209, 209, 209);
            min-height: 100%;
            display: grid;
            text-align: center;
            place-items: center;
        }
        .card {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-around;
            padding: 20px;
            font-family: 'Josefin Sans';
            color: white;
            box-shadow: 10px 10px 15px rgb(151, 150, 151), -10px -10px 15px white;
        }
        button{
            background-color: none;
            padding: 10px;
            outline: black;
            border: none;
            margin: 10px;
            font-family: 'Poppins';
        }
    </style>

And when that's done, the below will be the output.

Screenshot 2022-10-13 at 13-54-59 A Pen by Kelison.png

Now its time for the real fun part which is javascript. Before I get into the code, let me explain what we're going to do here. We are going to create a counter and set it's value to zero(0). And then we're going to use querySelectorAll to select all the above buttons and then use a forEach function to determine which button has been clicked and what to do when the button has been clicked.

let counter = 0;
let count = document.querySelector('.counter');
let buttons = document.querySelectorAll('.btn');
buttons.forEach((button)=>{
  button.addEventListener('click',()=>{
    if(button.classList.contains('btn-next')){
      counter++;
    }else if(button.classList.contains('btn-prev')){
      counter--;
    }
    count.textContent = counter;
  })
})

And when that's done, you should have a perfect JavaScript counter. You can check that out here

Thanks for reading. I hope you learned something. Follow for more.