How to Increment and Decrement Counter on Button Click in Javascript

In this tutorial, you will learn how to increment and decrement counter on button click in javascript. As you already know, increment means adding a certain number to an existing number and decrement means subtracting a certain number from an existing number.

For the sake of simplicity, we are going to increment and decrement by 1.  We will use arithmetic operators addition (+) and subtraction (-) operators to achieve that.

In the following example, we have 2 buttons, one for increment and another for decrement. Depending upon which button is clicked, we will add or subtract 1 from the value in the input field.  Please have a look over the code example and steps given below.

HTML & CSS

  • We have 4 elements in the HTML file and that includes div, 2 button, and input elements.
  • The div element is just a wrapper for the rest of the elements.
  • The inner text for the first button element is “-” and for the second button element, it is “+”.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>
  
  <div>
    <button id="subtract">-</button>
    <input type="number" value="0">
    <button id="add">+</button>
  </div>
  <script src="script.js"></script>
</body>
</html>
div {
    width: 20%;
    margin: auto;
}

input, button {
    display: inline-block;
    padding: 10px;
}

Javascript

  • We have selected both the button elements and input element using document.querySelector() and stored them in btnAdd, btnSubtract, and input variables respectively.
  • We have attached the click event listener to both the button elements.
  • In both the event handler functions, we are using the parseInt() method and passing the value of the input element as a parameter. This method returns an integer.
  • In the event handler function of add button, we are adding 1 to the integer and updating the value in the input field.
  • In the event handler function of subtract button, we are subtracting 1 from the integer and updating the value in the input field.
let btnAdd = document.querySelector('#add');
let btnSubtract = document.querySelector('#subtract');
let input = document.querySelector('input');

btnAdd.addEventListener('click', () =>{
  input.value = parseInt(input.value) + 1;
});

btnSubtract.addEventListener('click', () =>{
    input.value = parseInt(input.value) - 1;
});
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •