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?
With plain Javascript, the simplest is: document. onkeypress = function (e) { e = e || window. event; // use e.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With