For number inputs in HTML, is there any way to have it function such that the longer the user holds the stepper arrows, the larger the increment/step size becomes?
For example, we start out at step size=1, but after a few seconds of holding, it will ramp up to 5, 10, 20, ... etc.
Is this possible? Thanks!
The step attribute controls the quantity added to the value of the input when the stepper is activated.
Using the setInterval method, we can change this value every X milliseconds.
Using a listener for the input's mousedown event, we can start/stop the interval and reset the current step when the mouse is released.
Here's a sample:
const input = document.getElementById('my-stepper');
const label = document.getElementById('my-label');
const defaultStep = 1;
const maxStep = 100000;
let interval;
input.addEventListener('mousedown', () => {
interval = setInterval(() => {
const currentStep = Number(input.step);
if (currentStep < maxStep) {
input.step = currentStep * 10;
label.innerText = `Current step is ${input.step}`;
}
}, 1000);
});
input.addEventListener('mouseup', () => {
clearInterval(interval);
input.step = defaultStep;
label.innerText = `Current step is ${input.step}`;
});
<input id="my-stepper" type="number" step="1" value="0">
<p id="my-label">Current step is 1</p>
Basic idea is below using mouse event listeners.
const elem = document.querySelector("#num");
let timer;
elem.addEventListener("mousedown", (evt) => {
const inp = evt.target;
inp.dataset.step = inp.step;
const initialValue = Number(inp.value);
timer = window.setInterval(()=>{
const dir = Number(inp.value) > initialValue ? 100 : -100;
console.log(Number(inp.step) + dir);
inp.step = Number(inp.step) + dir;
},2000);
});
elem.addEventListener("mouseup", (evt) => {
if (timer) window.clearTimeout(timer);
const inp = evt.target;
inp.setAttribute('step', inp.dataset.step);
});
<input type="number" step="1" id="num">