How to see if a modifier key is being held down without catching the keydown event?

Viewed 1408

I know how to catch keyup and keydown events.

I want my program to see which modifier keys (eg: meta key, control key, alt key, etc.) are currently being held down even if the program didn't observe the keydown events of those keys.

I know that click events and other events can tell me which modifier keys were pressed down when they were fired off, but my program can't wait around for one to occur.

I need my program to check for the modifier keys regularly (say, every 100ms). How would I go about doing this? My program uses jQuery if that helps.

2 Answers

Late to the party, but since this shows up on Google, here's a partial solution that's one step closer. From this SO answer:

document.body.onkeydown = function(e) {
  if (e.which === 18) {
    alt_state.textContent = 'pressed';
  }
};

document.body.onkeyup = function(e) {
  if (e.which === 18) {
    alt_state.textContent = 'released';
  }
};

function detectAlt() {
  if (document.webkitHidden) return;
  window.addEventListener('mousemove', function onMove(e) {
    alt_state.textContent = e.altKey ? 'pressed' : 'released';
    window.removeEventListener('mousemove', onMove, false);
  }, false);
}

document.addEventListener('webkitvisibilitychange', detectAlt, false);
window.addEventListener('load', detectAlt, false);

Essentially, set up a mousemove event listener, which contains the modifier key states when fired, and remove the listener after it's fired the first time. Again, still requires an "event" but depending on your application's expected usage, catching the first mousemove event might be sufficient for detecting modifier keys.

Related