DEV Community

netsi1964 🙏🏻
netsi1964 🙏🏻

Posted on • Updated on

Extend input type=“number” with modifiers

Add keyboard modifiers to input type=“number”

When you use input type=“number” the user can change the number by the specified value of the value specified in the step attribute. I wanted the let the user step by default with 0.01 but also wanted the user to be able to hold down SHIFT and change by 0.1 and ALT/CMD to change by 1.00.

I added two event listeners for keydown to activate the modifier and keyup to disable the modifier.

// This is pretty neat!
// Changes the step value on the input type number step value
// No modifiers => step = .01
// SHIFT => step = 0,1
// ALT (or CMD) => step = 1
eleMatrix.addEventListener("keydown", (evt) => {
  const { altKey, shiftKey, metaKey } = evt as KeyboardEvent;
  const target = evt.target as HTMLInputElement;
  if (altKey || metaKey || shiftKey) {
    target.step = altKey || metaKey ? "1" : "0.1";
  }
});
eleMatrix.addEventListener("keyup", (evt) => {
  const { altKey, shiftKey, metaKey } = evt as KeyboardEvent;
  const target = evt.target as HTMLInputElement;
  if (altKey || metaKey || shiftKey) {
    target.step = altKey || metaKey ? "1" : ".1";
  } else {
    target.step = ".01";
  }
});

You can try out the effekt in this pen.

Top comments (0)