Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting a key press ignoring modifier keys

Tags:

javascript

I am implementing an idle timeout functionality for my website. I want to reset the idle timeout whenever the user interacts with the page, which I want to implement as "the user clicks anywhere on the page" or "the user types a key".

The following code works:

window.addEventListener('click', resetTimeout);
window.addEventListener('keydown', resetTimeout);

Unfortunately it detects modifier keys (alt, shift, ctrl, meta). I don't want to reset the timeout in these cases. For example, when the user alt+tab's to another window, the alt key resets the timeout.

An alternative to keydown is keypress, however, it is marked as deprecated. Is there an alternative for keypress, specifically for the situation I am describing?

like image 994
crazypeter Avatar asked Oct 25 '25 10:10

crazypeter


1 Answers

I came here looking for an answer but was not happy with having to maintain a list of exclusions so I solved this by checking the length of the key name.

window.addEventListener('keydown', resetTimeout);

function resetTimeout(args) {
    if (args.key.length === 1) {
        // 'a', 'A', '1', '.', '%' etc
    } else {
        // 'Alt', 'Control', 'Shift', 'Escape', 'Backspace' etc
    }
}

You can also use the next trick to isolate modifier keys from any other key. Thanks to @mikeypie for the suggestion.

function resetTimeout(args) {
    if (args.key.length === 1 || args.key === args.code) {
        // 'a', 'A', '1', '.', '%', 'Escape', 'Backspace' etc
    } else {
        // 'Alt', 'Control', 'Shift'
    }
}

This works because the args.code includes Left or Right for modifier keys,

e.g. when left Shift is pressed:

  • args.key: "Shift"
  • args.code: "ShiftLeft"
like image 70
Steven Liekens Avatar answered Oct 27 '25 01:10

Steven Liekens