Rashid Shaikh
Rashid Shaikh

Reputation: 415

Javascript onKeyDown function

I have written a simple javascript code and added event listener for onKeyDown/onKeyUp . It works just fine and detects the Control key as required. However the Control key shows pressed even when I am using OS shortcuts.

To be specific I am on Ubuntu and use Ctrl+Alt+ arrow keys to switch workspaces. So when I switch the workspace and come back to Chrome, it shows Control key pressed already.

I dont mind it but even when the shortcut keys are released, onkeyup method is not called and hence the status shows Ctrl key pressed. How do I avoid this?

Below is my code:

function keypressedfn(e){
if(e.which == CTRL_KEY){
    console.log("isCtrl pressed");
    isCtrl=true;
    if(isWheel){
        e.preventDefault();
        e.stopPropagation();
    }
}
};

function keyreleasedfn(e){
if(e.which == CTRL_KEY){
    console.log("isCtrl released");
    isCtrl=false;
    isWheel=false;
}
};

$(document).ready(function(){
$(document).keydown(keypressedfn);
$(document).keyup(keyreleasedfn);
});

Upvotes: 3

Views: 822

Answers (2)

sampathsris
sampathsris

Reputation: 22290

It is not standard practice to detect the KeyDown event of Control key (or Alt, or Shift, for that matter).

What you should do is find if your desired key is pressed. For example, if you want to save something when Ctrl+S is pressed, look for S key.

var keyCode = (e.which) ? e.which : e.keyCode; // keyCode will be 'S'

if (e.ctrlKey && keyCode == 83) {
    // Ctrl + S pressed. Do stuff.
}

Upvotes: 1

danyamachine
danyamachine

Reputation: 1908

if you're using Ctrl to change workspaces, then your window w/ js running is losing focus before the keyup event. you could bind an event to the window object that discards keydown whenever the window loses focus:

window.onblur = function(){console.log("blur");};

without seeing more of your code i can't say much more than that

Upvotes: 2

Related Questions