Javascript Quantity box with plus and minus buttons

Category: Text & Input | January 20, 2019
Author: awdltd
Official Page: Go to Website
Last Update:August 1, 2023
License:MIT

Are you planning to build an E-commerce website? Instead of adding boring quantity box, why not try out this beautiful and clean looking plus and minus buttons to stand out your site.

Its a quantity.js, a small and tiny javascript file which make the input quantity box a nice looking. All e-commerce website need quantity box,  where the user needs to define the number of the product that they want to add into the cart.

If you want to make a site with a good feel then this small script surely helps you to make the box more appealing.

Let’s give your site visitor something unique and enhance the beauty of your client website.

How to Implement Plus/Minus Quantity Box

The implementation is quite easy and simple. You need to import two files and the first one is a style.css in the document.

<link href="style.css" rel="stylesheet" type="text/css" />

Next, You have to Import the Javascript quantity Input as a module.

<script type="module">
  import QuantityInput from './quantity.js';
</script>

Now you are ready to create the HTML for input and all you have to define the fieldset element and define the data-quantity attribute.

<fieldset data-quantity>
  <legend>Change quantity</legend>
</fieldset>

Finally, The last and important part is Javascript which makes work the quantity box with plus and minus buttons.

(function(){
  let quantities = document.querySelectorAll('[data-quantity]');

  if (quantities instanceof Node) quantities = [quantities];
  if (quantities instanceof NodeList) quantities = [].slice.call(quantities);
  if (quantities instanceof Array) {
    quantities.forEach(div => (div.quantity = new QuantityInput(div, 'Down', 'Up')));
  }
})();