ulu
ulu

Reputation: 6092

Getting the character from keyup event

I'm handling the keyup event, and need to get the character being typed. When I type a dot, data.keyCode is 190, but when I'm trying to convert it using String.fromCharCode(190), I'm getting the "¾" symbol.

This reference tells me 190 is the period symbol. That one says I don't have any chance for cross-browser keypress handling. So, how do I handle this properly?

Upvotes: 4

Views: 4729

Answers (1)

bobince
bobince

Reputation: 536339

I'm handling the keyup event, and need to get the character being typed.

That's not reliably available. On keyup you only get the keyCode and not the charCode.

(If you think about it this makes sense: the charCode is associated with the character being typed in a keypress, which might be shifted with a modifier key and so generate a different character to the base key; on keyup and keydown, since those events are not immediately associated with a new character being typed, there isn't a known character to generate.)

So if you are doing something that relies on knowing whether a . character was typed, you will need to use the keypress event instead.

If you want to know when the abstract key that is labelled ./> on some common keyboard layouts is released, you can do that with keyup, using the keyCode listed on the unixpapa link. Using keyCode like this is typically used for games and other features where the actual key position matters rather than the character it generates when typed.

Unfortunately the browsers have made an inconsistent mess of some keyCodes including this one, so you'd have to check it for all possible values listed above, and you can't reliably tell the difference between the main keyboard period, the numpad period/delete key and the main delete key.

Upvotes: 5

Related Questions