Build Counter that Increment and Decrement on button hold (pressed) with JavaScript.

0

In this blog post, we'll delve into creating increment and decrement counters using JavaScript. While I've previously shared a basic version of this counter, we'll now explore a more enhanced implementation.


increment and decrement counter


This counter has two distinct buttons: one dedicated to incrementing the value, and the other designed for decrementing it. These buttons have functionality that when a user holds down either button for longer than a second, the counter automatically begins to adjust the value continuously until the mouse button is released.

I've created button holds functionality with settimeout method of javascript. Read further for more understanding.


Javascript methods used:

Settimeout

Setinterval

Value

Increment 

Decrement


Javascript events used:

Onmouseup

Onmousedown

Onmouseleave

Onclick



Video on Increment and Decrement Counter.



Increment And Decrement Counter.

Explanation of how we will create the counter:

  • First, we will create a simple increment and decrement counter. When a user clicks a button, the counter will increment or decrement the value accordingly.
  • We begin by defining a variable named i and setting its initial value to zero.
  • Then we will create a function that executes when the increment button (plus button) is clicked. Inside this function, we will Increment the value of the variable i by 1. And add the updated value of i to the input field.
  • Similarly, we will create a function that runs when the decrement button (minus button) is clicked. Within this function, we will decrement the value of the variable i by 1. And add the new value of i to the input field.

With these steps, we will have successfully implemented a simple increment and decrement counter.


HTML


<!DOCTYPE html>
<html lang="en">
<!-- maketechstuff.com -->

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Increment and decrement counter. | maketechstuff.com</title>
    <link rel="stylesheet" href="index.css">
</head>

<body>
    <h2 style="text-align: center; padding-top: 250px; color: #fff; font-size: 30px;">Maketechstuff.com</h2>

    <div class="box">
        <button type="button" class="minus">-</button>

        <div class="input_box">
            <input type="text" class="input_field" value="0" readonly>
        </div>

        <button type="button" class="plus">+</button>
    </div>

</body>
</html>

CSS


* {
    padding: 0px;
    margin: 0px;
}

body {
    width: 100%;
    height: 100%;
    background-color: blue;
}

.box{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50% , -50%);
    background-color: #fff;
    width: 400px;
    border-radius: 3px;
    padding: 35px;
    box-shadow: 0px 5px 10px -5px #000;
    display: flex;
}

.input_box{
    margin: 0px 20px;
    display: flex;
}

input{
    width: 100%;
    padding: 10px 15px;
    font-size: 35px;
    text-align: center;
    outline: none;
}

button{
    font-size: 40px;
    padding: 5px 30px;
    background-color: blue;
    color: #fff;
    border: none;
    border-radius: 3px;
    cursor: pointer;
    transition: 0.1s;
}

button:active{
    transform: scale(0.9);
}

JavaScript


    let minus = document.querySelector(".minus");
    let input_field = document.querySelector(".input_field");
    let plus = document.querySelector(".plus");

    let i = 0;

    plus.onclick = function () {
        i++;
        input_field.value = i;
    }
    minus.onclick = function () {
        if (i != 0) {
            i--;
            input_field.value = i;
        }
    }

Output:




As you can see, the increment and decrement functionality of the counter is working. However, it currently only changes the counter by one with each individual click. Let's enhance the counter to count continuously while a button is held down.


Incrementing and decrementing a counter while a button is held down


Explanation of the implementation:

  • First we attach a function to the onmousedown event. This function will initiate the incrementing process when the button is pressed down.
  • Within this function, we’ll add setTimeout to introduce a slight delay: This delays the counter to start incrementing. This act like a button holds functionality.
  • Clear the timeout using clearTimeout on mouseup, If not cleared then a single click event (less than set timeout) can trigger the function inside the settimeout.
  • Within the setTimeout method, we’ll call a function to increment the counter: This function handles the actual value updates.
  • In that function we’ll add setInterval with a 0.1-second interval to increment the counter. This method repeatedly calls a function every 0.1 seconds, leading to a continuous increment while the button is held.
  • Inside the setInterval function, add the value of the i variable to the input field. This effectively displays the incremented value.
  • Now the counter is working but we also have to stop it when the user releases the button. So for that we’ll attach onmouseup and mouseleave events to the increment button. These events trigger when the button is released or when the mouse leaves the increment button area (plus button), respectively.
  • Within these event handlers, we’ll clear the interval using clearInterval. This stops the incrementing process, preventing further updates.
  • Attaching event handlers to both onmouseup and mouseleave ensures the counter stops even if the mouse is released outside of the button.


So that's for incrementing the counter continuously on while a button is pressed.


We’ll do a similar process for decrement counting too.


See below code for better understanding.


JavaScript


    // Increment.
    plus.onmousedown = function () {
        let plus_button_hold = setTimeout(() => {
            increase_counter();
        }, 1000);
        plus.onmouseup = function () {
            clearTimeout(plus_button_hold);
        }
    }

    function increase_counter() {
        let increase = setInterval(() => {
            i++;
            input_field.value = i;
        }, 100);

        plus.onmouseup = function () {
            clearInterval(increase);
        }
        plus.onmouseleave = function () {
            clearInterval(increase);
        }
    }

    // Decrement.
    minus.onmousedown = function () {
        let minus_button_hold = setTimeout(() => {
            decrease_counter();
        }, 1000);
        minus.onmouseup = function () {
            clearTimeout(minus_button_hold);
        }
    }

    function decrease_counter() {
        let decrease = setInterval(() => {
            if (i != 0) {
                i--;
                input_field.value = i;
            }
        }, 100);

        minus.onmouseup = function () {
            clearInterval(decrease);
        }
        minus.onmouseleave = function () {
            clearInterval(decrease);
        }
    }

Output:




Final code:



This is how you can create an increment and decrement counter that counts until the button is released. If you have any questions or suggestions, feel free to write in the comment section.


You may like:

  1. How to increment and decrement the counter using JavaScript.
  2. How to create a countdown timer with fade out animation using JavaScript.
  3. How to create a character counter using JavaScript.
  4. How to create a word counter using JavaScript.



Tags

Post a Comment

0Comments

Share your thoughts.

Post a Comment (0)
To Top