0

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

3
  • 1
    Are you checking for the right keycodes? (46 is the code for "delete", though some keyboards will send "backspace" (keycode 8) instead...) It may be better to use event.which which is a little bit more standardized. Commented Oct 6, 2018 at 15:12
  • Yes I'm aware thats the del button, i was testing all the buttons, yes i was aware of a scenario like you mentioned, i even did another test exercise to make sure that the input was correct, i printed on the browser what ever the input was so if i press delete it would print 46 with alert message and it all works.. but i cant see why it doesnt work with the original example.. thanks for the input i will try out the event.which Commented Oct 7, 2018 at 16:11
  • In that case I'm unclear on what you mean by "it doesn't work". Commented Oct 8, 2018 at 18:47

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the input, it works but only when i use "." i tried "32" for instance but no luck, i will look into the document thanks.
No, you don't want "32" you want " ".
Play with it by opening the js console in your browser on this page, and type as one line: document.addEventListener("keypress", function(e){ console.log(e.code, e.key); if(e.key==window.myKey)alert(e.key)}); Then type myKey=" ". Then type in the document, e,g, by adding a comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.