سؤال

I am building a program in JavaScript. While I tried to add keyevents, but when I was done and tried to move my object it didn't move. I tried to figure out what the problem was while I tried to move a object (with x and y coordinate system for example(y[1] += 5;)). Therefore I did try to see so the keycode was right. I made a function to see the keyCode:

window.addEventListener( "keypress", doKeyDown, false );   
 
function doKeyDown(e) {
    alert( e.keyCode )
}

Then I tried to press any button to see the keycode but every button is saying "0", unless arrow up, down, right, left. They are telling me the same value as on this website: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes but as I said for example "W" "A" "S" "D" just tell me "0" as the keycode and I wounder why.

هل كانت مفيدة؟

المحلول

Use charCode instead of keyCode for characters.

The charCode property is holding the ascii of the character you can use to retrieve the pressed letter with String.fromCharCode.

Keycodes and charcodes are different things and you can use this difference to determine if the user typed a character or accomplished an action such as when using arrows.

نصائح أخرى

Use window.addEventListener("keydown", doKeyDown, false); instead. It will report the keycodes listed on the page you linked. Otherwise, the keycodes are different.

The 'keydown' event reports a key code for any key pressed and is case-insensitive.

  • 'e' = 69 and 'E' = 69
  • '[Num Lock]' = 144
  • '[Backspace]' = 8

The 'keypress' event appears to only report key presses for printable characters (carriage return included) and the key code is then also case sensitive.

  • 'e' = 101 and 'E' = 69
  • '[Num Lock]' has no value.
  • '[Backspace]' has no value.

Here's a JS Fiddle example showing the values reported by both events.

This was tested in Chrome

You should (in some styling opinions) declare your function before using it in your event listener, although all browsers will hoist this, it will give you errors if you use jslint though.

'doKeyDown' was used before it was defined.

Here is one of many answers giving information of the above: JSLint: Using a function before it's defined error

Here is an example, on jsfiddle

<input id="input" type="text"></input>

console.log("W", "W".charCodeAt());

function logIt(evt) {
    console.log(String.fromCharCode(evt.charCode), evt.charCode);
}

var input = document.getElementById("input");

input.addEventListener("keypress", logIt, false);

You may also want to take a read of the following answer, there are others, regarding different event types keypess and keydown, and the properties charCode and keyCode:

JavaScript KeyCode vs CharCode

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top