DEV Community

netsi1964 🙏🏻
netsi1964 🙏🏻

Posted on • Edited 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.

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs