Sarbbottam
Sarbbottam

Reputation: 5580

e.keyCode in iOS Safari on keyup event

Update

I have been trying so far in the simulator along physical keyboard. That was causing the problem. However with soft keyboard it works as desired. keyup event has a well defined keyCode.


Please find the code at this pen

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

var test = document.getElementById('test'); test.addEventListener('keyup', function(e) { alert(e.keyCode); });

iOS safari display 0 as the keyCode for any key pressed (keyup event). Any pointer would be very helpful.

Update

e.keyCode as well as e.which works with keypress event, but I could not get it to work with keyup event.

Upvotes: 3

Views: 11061

Answers (3)

Eric Boehs
Eric Boehs

Reputation: 1327

I was able to get it to work with keyup and keydown by using e.key which returns the key pressed (e.g. / or a).

I was able to figure this out by inspecting the event object using the remote debugger.

I checked in the latest Chrome, Firefox, iOS Safari, and macOS Safari and they all report the key via e.key.

Edit:

keyup and keydown aren't working now. I think I glitched it with the remote debugger or something. I have, however, figured out an alternative solution which works for my use case.

I wanted to focus an input when / was pressed. I went with the above solution of binding to keypress but the key was entered into the input since the keyup event hadn't fired. Simply calling e.preventDefault() solved my issue nicely. I can still match on e.key == '/' with the keypress event too!

Upvotes: 0

Sarbbottam
Sarbbottam

Reputation: 5580

e.keyCode is present in the keyup event in iOS safari, in actual device as well as simulator. However in simulator, if physical keyboard is used, e.keyCode is set to zero.enter image description here

Upvotes: 7

blex
blex

Reputation: 25634

Use e.which instead of e.keyCode.

Edit: To normalize this value, you could use e.keyCode || e.which.

Upvotes: 5

Related Questions