Home > Enterprise >  Check for alt key js
Check for alt key js

Time:10-31

I want to see if the alt key and j(or any other number or letter) key are being pressed at the same time.

Here's what I have so far:

document.onkeydown = function(e) { 
    if(e.altKey && e.keyPressed == "j") {
        console.log("alt   j pressed")
    }
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

This isn't working.

Any help on this?

CodePudding user response:

You should be getting the event's key property instead:

document.onkeydown = function(e) { 
    if(e.altKey && e.key == "j") {
        console.log("alt   j pressed")
    }
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

That's because a KeyboardEvent does not have a keyPressed property. There is a key property that indicates which key was pressed.

CodePudding user response:

Maybe it works

var altKeyPressed = false;
document.addEventListener("keydown", function(e) {if(e.altKey) {
        altKeyPressed = true;
    }});
document.addEventListener("keydown", function(e) {if(e.key === "j" && altKeyPressed) {
        console.log("alt   j pressed");
        altKeyPressed = false;
    }});
  • Related