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