Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect @ character onKeyUp in Edge on any keyboard

In most browsers on my qwerty keyboard, event.key of shift + 2 is "@" from the keyup key event. However, Edge reports event.key: "2". So I could just put down something like

if(event.key == "2" && event.shiftKey){
  //code to execute when "@" key is down
}

which works great until one a user with a keyboard from a country like Germany or Hungary, or probably many others comes and expects my code to work on Edge when they type an "@" character but instead of shift + 2, they use some other key combination.

How can I reliably detect the "@" character from an onKeyUp event in Edge given that some keyboard layouts do not produce an @ character from shift + 2?

Is there a way to detect that a user is using a keyboard that has an alternate layout and is there some list of layouts from which I could create some probably obscenely long switch statement to map the "shift + 2" code for any given combo per keyboard layout?

I need this to work in onKeyUp, not onKeyDown.

This is what Edge gives me with shift + 2 onkeyup.

[object KeyboardEvent]: {altKey: false, bubbles: true, cancelable: true, cancelBubble: false, charCode: 0...}
altKey: false
bubbles: true
cancelable: true
cancelBubble: false
charCode: 0
ctrlKey: false

currentTarget: Object
defaultPrevented: false
detail: 0
eventPhase: 3
isTrusted: true
key: "2"
keyCode: 50
location: 0
metaKey: false
repeat: false
returnValue: true
shiftKey: true

srcElement: Object

target: Object
timeStamp: 69676.72914431277
type: "keyup"

view: Object
which: 50

__proto__: Object

Below is an image of a German keyboard. Note the position of the @ char. I don't want to support just German and American, I want to support any keyboard.

German keyboard

On Edge in onKeyUp, event.charCode is always 0, event.key is 2 even when the shift key is down when trying to type @, and event.char is always undefined. See this Codepen as a starting place using the Edge browser: https://codepen.io/glenpierce/pen/QmNQRq?editors=1111#

like image 511
Glen Pierce Avatar asked Mar 02 '18 21:03

Glen Pierce


1 Answers

You can test this:

Edit: If we are looking for @ char (which its not always shift + 2)

//in edge is char, the rest has character in key. In some cases you can use charCode
if(event.key == '@' || event.char == '@' || event.charCode == '@') {

 }
like image 54
Saeed.Gh Avatar answered Sep 20 '22 23:09

Saeed.Gh