Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 444
zurk Avatar asked Sep 17 '08 03:09

zurk


People also ask

How do you press a button in JavaScript?

The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.

How do you press and hold?

Press and hold means pressing the key for 1 or more seconds. Press and hold means to press and hold a key for 2-3 seconds, then release the key.

Can we click button using JavaScript?

Javascript has a built-in click() function that can perform a click in code.

How does a button work in JavaScript?

The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button.


1 Answers

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 */
like image 139
neouser99 Avatar answered Oct 11 '22 18:10

neouser99