Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a key pressed for x seconds in javascript?

I need to detect when a user keep press a button for X second and call function in JavaScript. Could you point me out in right direction?

like image 675
GibboK Avatar asked Aug 05 '14 08:08

GibboK


People also ask

How do you detect if a key has been pressed in JavaScript?

With plain Javascript, the simplest is: document. onkeypress = function (e) { e = e || window. event; // use e.

How do you check if pressed key is enter?

keyCode === 13) { console. log('Enter key pressed') } }); to check if the key with key code 13 is pressed. If it is, then we know the enter key is pressed.

Do something when key is pressed JavaScript?

There are three different keyboard events in JavaScript: keydown : Keydown happens when the key is pressed down, and auto repeats if the key is pressed down for long. keypress : This event is fired when an alphabetic, numeric, or punctuation key is pressed down. keyup : Keyup happens when the key is released.

Which event captures a keypress in JavaScript?

The onkeypress event occurs when the user presses a key (on the keyboard). Tip: The order of events related to the onkeypress event: onkeydown. onkeypress.


1 Answers

You can use a setTimeout function on the keydown event which will fire after X seconds to compare the time that event was triggered to the last time a keyup was triggered - if at all.

var lastKeyUpAt = 0;

$(elem).on('keydown', function() {
    // Set key down time to the current time
    var keyDownAt = new Date();

    // Use a timeout with 1000ms (this would be your X variable)
    setTimeout(function() {
        // Compare key down time with key up time
        if (+keyDownAt > +lastKeyUpAt)
            // Key has been held down for x seconds
        else
            // Key has not been held down for x seconds
    }, 1000);
});

$(elem).on('keyup', function() {
    // Set lastKeyUpAt to hold the time the last key up event was fired
    lastKeyUpAt = new Date();
});

elem here is the element you're wanting to handle the event on.

JSFiddle demo.

like image 148
James Donnelly Avatar answered Oct 04 '22 05:10

James Donnelly