Search code examples
javascriptmouse

Need javascript code for button press and hold


I'd like a short smallest possible javascript routine that when a mousedown occurs on a button it first responds just like a mouseclick and then if the user keeps the button pressed it responds as if the user was continously sending mouseclicks and after a while with the button held down acts as if the user was accelerating their mouseclicks...basically think of it like a keypress repeat with acceleration in time.
i.e. user holds down mouse button (x=call function) - x___x___x___x__x__x_x_x_x_xxxxxxx


Solution

  • function holdit(btn, action, start, speedup) {
        var t;
    
        var repeat = function () {
            action();
            t = setTimeout(repeat, start);
            start = start / speedup;
        }
    
        btn.mousedown = function() {
            repeat();
        }
    
        btn.mouseup = function () {
            clearTimeout(t);
        }
    };
    
    /* to use */
    holdit(btn, function () { }, 1000, 2); /* x..1000ms..x..500ms..x..250ms..x */