I've been doing a bit of work with Javascript key events (keyup, keydown, keypress) and have concluded that each has their advantages and disadvantages when trying to determine what key(s) the user has pressed.
By using event.which as provided by jQuery it would seem that onkeypress will provide character codes that are case sensitive. i.e. 65-90 for A-Z and 97-122 for a-z. However, special keys such as the directional don't trigger onkeypress. They however will trigger a keyup/*keydown*, but those won’t provide case sensitive codes.
Does there exist a "best of both worlds" solution that will provide both case sensitive and special key detection that does not require manual simultaneous monitoring of several events?
When listening for the keyup event
$(document).on('keyup', on_key_up);
function on_key_up(event)
{
console.log('keycode:',event);
}
i log this:
altKey: false
bubbles: true
cancelable: true
char: undefined
charCode: 0
ctrlKey: false
currentTarget: document
data: undefined
delegateTarget: document
eventPhase: 3
handleObj: Object
isDefaultPrevented: function ot(){return!1}
jQuery19106670567644760013: true
key: undefined
keyCode: 69
metaKey: false
originalEvent: KeyboardEvent
relatedTarget: undefined
shiftKey: false
target: body
timeStamp: 1367933052234
type: "keyup"
view: Window
which: 69
You want the keyCode (69 in this case), shifKey, altKey, ctrlKey. example: If you press shift+arrow right, you will get keyCode:3, shiftKey:true.
function on_key_up(event)
{
if(event.shiftKey) // action
}
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With