select
select

Reputation: 2618

Time length of key pressed down

Is is possible to find out the time of how long a key is pressed down? I want to call a function after the ctrl key is pressed for one second.

Upvotes: 0

Views: 107

Answers (1)

Nic
Nic

Reputation: 581

Try this:

var timeout;

document.onkeydown = function() {
    if (!timeout) {
        timeout = window.setTimeout(function() {
            timeout = null;
            alert("pressed for a second");
        }, 1000);
    }
}

document.onkeyup = function() {
    window.clearTimeout(timeout);
}

You just have to add the check whether or not it's the CTRL key that is pressed (in both event handlers of course.)

Upvotes: 2

Related Questions