CoderGuruXYZ
CoderGuruXYZ

Reputation: 73

Check for alt + key js

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")
    }
}

This isn't working.

Any help on this?

Upvotes: 1

Views: 63

Answers (3)

sh kashani
sh kashani

Reputation: 87

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

Upvotes: 1

Spectric
Spectric

Reputation: 31992

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")
    }
}

Upvotes: 2

Brother Woodrow
Brother Woodrow

Reputation: 6372

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

Upvotes: 1

Related Questions