Convineint Number Spinner Control In Pure JS – Increment Stepper

Category: Form , Javascript | August 17, 2018
Author:MindzGroupTechnologies
Views Total:5,106 views
Official Page:Go to website
Last Update:August 17, 2018
License:MIT

Preview:

Convineint Number Spinner Control In Pure JS – Increment Stepper

Description:

The pure JavaScript/CSS increment stepper converts the normal number input into a spinner control with increment and decrement buttons.

Supports the native min/max and step attributes.

How to use it:

Wrap the number input together with increment and decrement buttons into an element.

<span class="stepper">
  <button>–</button>
  <input type="number" id="stepper" value="5" min="0" max="100" step="2" readonly>
  <button>+</button>
</span>

The necessary CSS styles.

[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  height: auto;
}
.stepper {
  border: 1px solid #eee;
  display: inline-block;
  overflow: visible;
  height: 2.1em;
  background: #fff;
  padding: 1px;
}
.stepper input {
  width: 3em;
  height: 100%;
  text-align: center;
  border: 0;
  background: transparent;
  color: #000;
}
.stepper button {
  width: 1.4em;
  font-weight: 300;
  height: 100%;
  line-height: 0.1em;
  font-size: 1.4em;
  padding: 0.2em !important;
  background: #eee;
  color: #333;
  border: none;
}

The main JavaScript to activate the spinner control.

var inc = document.getElementsByClassName("stepper");
for (i = 0; i < inc.length; i++) {
  var incI = inc[i].querySelector("input"),
    id = incI.getAttribute("id"),
    min = incI.getAttribute("min"),
    max = incI.getAttribute("max"),
    step = incI.getAttribute("step");
  document
    .getElementById(id)
    .previousElementSibling.setAttribute(
      "onclick",
      "stepperInput('" + id + "', -" + step + ", " + min + ")"
    ); 
  document
    .getElementById(id)
    .nextElementSibling.setAttribute(
      "onclick",
      "stepperInput('" + id + "', " + step + ", " + max + ")"
    ); 
}
function stepperInput(id, s, m) {
  var el = document.getElementById(id);
  if (s > 0) {
    if (parseInt(el.value) < m) {
      el.value = parseInt(el.value) + s;
    }
  } else {
    if (parseInt(el.value) > m) {
      el.value = parseInt(el.value) + s;
    }
  }
}

You Might Be Interested In:


One thought on “Convineint Number Spinner Control In Pure JS – Increment Stepper

  1. Godfrey

    stepper will go above max and below min at times. Start the stepper at 1 and increment by 2 to test. Possible fix:

    function stepperInput(id, s, m) {
    var el = document.getElementById(id);
    if (s > 0) {
    if (parseInt(el.value) < m && (parseInt(el.value) + s m && (parseInt(el.value) + s >= parseInt(el.min))) {
    el.value = parseInt(el.value) + s;
    } else {
    e.valie = el.min;
    }
    }
    }

    Reply

Leave a Reply