This code should do whatever you are looking for; it was very weakly based on the example of tj111. I tried to make it as reusable as possible, and it doesn't need JavaScript mixed with HTML.
You need to add identifiers to the buttons ( btnUP and btnDOWN ) and the text field ( amount ). You can change these identifiers in the window.onload statement.
// This function creates a closure and puts a mousedown handler on the element specified in the "button" parameter. function makeButtonIncrement(button, action, target, initialDelay, multiplier){ var holdTimer, changeValue, timerIsRunning = false, delay = initialDelay; changeValue = function(){ if(action == "add" && target.value < 1000) target.value++; else if(action == "subtract" && target.value > 0) target.value--; holdTimer = setTimeout(changeValue, delay); if(delay > 20) delay = delay * multiplier; if(!timerIsRunning){ // When the function is first called, it puts an onmouseup handler on the whole document // that stops the process when the mouse is released. This is important if the user moves // the cursor off of the button. document.onmouseup = function(){ clearTimeout(holdTimer); document.onmouseup = null; timerIsRunning = false; delay = initialDelay; } timerIsRunning = true; } } button.onmousedown = changeValue; } //should only be called after the window/DOM has been loaded window.onload = function() { makeButtonIncrement(document.getElementById('btnUP'), "add", document.getElementById('amount'), 500, 0.7); makeButtonIncrement(document.getElementById('btnDOWN'), "subtract", document.getElementById('amount'), 500, 0.7); }
s4y
source share