Javascript keyCode

101 views Asked by At

i have a problem with keyCode in javascript i used this exact code from tutorial

document.addEventListener("keypress", keypressed);

function keypressed(event){
    if(event.keyCode === 46){
        alert("key pressed")
    }
}

but it doesn't work for me (it works in the tutorial), however when i tried to use enter which is 13 and space which is 32 both work, but not a-z or numbers or anything else, any idea why? Thanks in advance

1

There are 1 answers

3
Chris F Carroll On

Alas, your tutoral is out of date.

Fortunately, MDN is a good source for accurate information on javsacript and for keyCode it says, “keyCode is deprecated, don't use it.

Instead, use key for keystrokes or code for keyboard codes:

function keypressed(event){
    if(event.key=== "."){
        alert("key pressed")
    }
}

Note, with event.key you use the literal character, not the code: " " instead of 32.