Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect pressed modifier keys without triggering keyboard or mouse events

My app changes its state when a person holds modifier keys (Shift, Alt, Ctrl). I track modifier keys using keydown/keyup events:

var altPressed;
window.onkeydown = window.onkeyup = function(e) {
    altPressed = e.altKey;
}

Keyboard events don’t trigger outside of the browser tab. Now, imagine the following scenario:

  1. Hold Shift key
  2. Click on a link to my app, it will open in a new window
  3. Release Shift key

keyup event won’t fire on my page when it isn’t focused so my app will show when I focus on my app’s tab again it will show the Shift key still being pressed.

Would be nice if page visibility events had modifier key properties. Alas, they don’t.

document.addEventListener('webkitvisibilitychange', function(e) {
    if (document.webkitHidden) return;

    e.altKey // undefined :(

}, false);
like image 338
NVI Avatar asked Feb 28 '14 04:02

NVI


1 Answers

The best I came up so far:

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);

Press alt key and click on the link: jsbin.

It relies on mousemove event which, unlike load and visibilitychange events, has altKey property. As a downside, it won’t detect altKey until a person moves the mouse.

like image 184
NVI Avatar answered Sep 23 '22 21:09

NVI