Increment and Decrement Counter in JavaScript

Increment and Decrement Counter in JavaScript

Hello Coders! Welcome to JS Project Blog. In this, we're going to see how to create an Increment and Decrement Counter using JavaScript. This type of counter is very popular in E-commerce and Shopping websites which allows you to increase or decrease the quantity of the product you like to purchase.

Here's a preview-

CodePen - Increment Counter.gif

That being said, let us get started.

Step - 1: Like always, create 3 files - index.html, style.css and script.js

Step - 2: Copy the below HTML code and paste it into your code editor.

HTML

<body>
  <div class="wrapper">
    <span class="minus">-</span>
    <span class="num">01</span>
    <span class="plus">+</span>
  </div>
</body>

Step - 3: Below is the CSS code for styling.

CSS

/* Google fonts import link */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins',sans-serif;
}
body{
  height: 100vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #343F4F;
}
.wrapper{
  height: 120px;
  min-width: 380px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #FFF;
  border-radius: 12px;
  box-shadow: 0 5px 10px rgba(0,0,0,0.2);
}
.wrapper span{
  width: 100%;
  text-align: center;
  font-size: 55px;
  font-weight: 600;
  cursor: pointer;
  user-select: none;
}
.wrapper span.num{
  font-size: 50px;
  border-right: 2px solid rgba(0,0,0,0.2);
  border-left: 2px solid rgba(0,0,0,0.2);
  pointer-events: none;
}

Step - 3: Below is the jQuery code for adding and removing the class.

JS

const plus = document.querySelector(".plus"),
    minus = document.querySelector(".minus"),
    num = document.querySelector(".num");
    let a = 1;
    plus.addEventListener("click", ()=>{
      a++;
      a = (a < 10) ? "0" + a : a;
      num.innerText = a;
    });

    minus.addEventListener("click", ()=>{
      if(a > 1){
        a--;
        a = (a < 10) ? "0" + a : a;
        num.innerText = a;
      }
    });

And that's it. You're done.

Let me know in the comments if you have any doubt related to this.

Follow @creocodigo for more projects and web related content.

If you find this useful, below are some other posts that I am sure you'll love