Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This code should do everything you're looking for; it's based very loosely on tj111's example. I tried to make it as reusable as possible, and it doesn't need JavaScript mixed in with the HTML.</p> <p>You do need to add IDs to the buttons (<code>btnUP</code> and <code>btnDOWN</code>) and text field (<code>amount</code>). You can change these IDs in the <code>window.onload</code> statement.</p> <pre><code>// 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" &amp;&amp; target.value &lt; 1000) target.value++; else if(action == "subtract" &amp;&amp; target.value &gt; 0) target.value--; holdTimer = setTimeout(changeValue, delay); if(delay &gt; 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); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload