1

I'm working on a mobile web app that requires an input field that wraps text. So I thought I'd use div with contenteditable.

JSFiddle: https://jsfiddle.net/9r5u7fgs/

<div
  class="text-field"
  contenteditable="true"
/>

The "input" field should only be 1 line, so when the user presses "enter" I want to trigger a POST request with the field contents. I don't want any newlines in the field.

I thought about listening for keyup and checking the keyCode. This works correctly on desktop.

document.addEventListener("keyup", function(e) {
    console.log(`e.keyCode=${e.keyCode} - e.key=${e.key}`);
    if (e.keyCode === 13) {
        sendContents(e.target.textContent);
    }
});

However on mobile browsers, I get different behavior.

  • First, the keyCode is always 229 for letters.
  • Second, I have to press enter twice to get the expected keyCode.

This is what Android 13 Firefox 108.2.0 shows if I type f <enter> <enter>.

e.keyCode=229 - e.key=Process
e.keyCode=229 - e.key=Process
e.keyCode=13 - e.key=Enter

Android Chrome 108.0.5359.128 prints something similar.

e.keyCode=229 - e.key=Unidentified
e.keyCode=229 - e.key=Unidentified
e.keyCode=13 - e.key=Enter

I found this: Keycode value is return as 229 for all keys but it didn't really provide a solution.

Is there a way to detect when a user presses "enter" the first time in a div contenteditable? Is there another event I should listen to?

Reminder this is for mobile web browsers, not desktop.

425nesp
  • 6,936
  • 9
  • 50
  • 61
  • Works as expected: Firefox 108.2.0, Android 12, Keyboard: Fleksy 10.2.7. Note for Chrome: Keycode for chars is allways 229 (as you say), but enter is 13 immediately. Have you used the OS default keyboard? – Marc Jan 18 '23 at 09:34

0 Answers0