Search code examples
javascriptkeyboard-eventsonfocus

Can I detect if key is being held down when window gains focus?


I am tracking keyDown and keyUp to show whether or not the shift key is being pressed in JavaScript:

window.addEventListener("keydown",doKeyDown,false);
window.addEventListener("keyup",doKeyUp,false);
var shiftKeyDown = false;

function doKeyDown(e) {
    if (e.keyCode==16) { shiftKeyDown = true; }
}

function doKeyUp(e) {
    if (e.keyCode==16) { shiftKeyDown = false; }
}

However, the user might hold the shift key down while giving focus to another window, so my window never hears the keyup event. Am I right in thinking that there is no way to detect the state of the shift key when the window gains focus again, so I can correctly update shiftKeyDown?


Solution

  • You can add a window.onBlur eventlistener and set shiftKeyDown to false, when the windows loses focus.

    window.addEventListener("blur",onBlur,false);
    function onBlur(e){ 
        shiftKeyDown = false 
    }