Products Quantity Counter Using HTML CSS & JavaScript

Hello, guys in this tutorial we will create a Products Quantity Counter Using HTML CSS & JavaScript.

First, we need to create two files index.html and style.css then we need to do code for it.

Products Quantity Counter Step:1

Add below code inside index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Products Quantity Counter</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta https-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans&display=swap" rel="stylesheet">
  </head>
  <body>
    <div class="counter">
      <span class="down" onClick='decreaseCount(event, this)'>-</span>
      <input type="text" value="1">
      <span class="up"  onClick='increaseCount(event, this)'>+</span>
    </div>
    <script type="text/javascript">
      function increaseCount(a, b) {
        var input = b.previousElementSibling;
        var value = parseInt(input.value, 10); 
        value = isNaN(value)? 0 : value;
        value ++;
        input.value = value;
      }
      function decreaseCount(a, b) {
        var input = b.nextElementSibling;
        var value = parseInt(input.value, 10); 
        if (value > 1) {
          value = isNaN(value)? 0 : value;
          value --;
          input.value = value;
        }
      }
    </script>
  </body>
</html>

Products Quantity Counter Step:2

Then we need to add code for style.css which code i provide in below screen.

* {
  padding: 0;
  margin: 0;
  font-family: 'IBM Plex Sans', sans-serif;
}
body {
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
}
.counter {
    width: 150px;
    margin: auto;
    display: flex;
    align-items: center;
    justify-content: center;
}
.counter input {
    width: 50px;
    border: 0;
    line-height: 30px;
    font-size: 20px;
    text-align: center;
    background: #0052cc;
    color: #fff;
    appearance: none;
    outline: 0;
}
.counter span {
    display: block;
    font-size: 25px;
    padding: 0 10px;
    cursor: pointer;
    color: #0052cc;
    user-select: none;
}

Products Quantity Counter Output:

Leave a Comment