javascriptdom-events

How to detect an 'Enter' key press in a textarea on mobile (Chrome on Android)


I'm trying to detect whenever the 'Enter' key is pressed within a textarea. On desktop, I can listen for the keydown event and and check if e.key === 'Enter' or e.keyCode === 13.

However this doesn't seem to work reliably on mobile (Chrome on Android).

If I input a few characters and press 'Enter', key is undefined and keyCode is 229 (Screenshot). keyCode 229 appears to be the same for any key.

What's strange is that if I end the last word with a period or space, then press 'Enter', both key and keyCode seem to capture that 'enter' was pressed (Screenshot)

I've also tried listening for the beforeinput event and checking e.inputType === 'insertLineBreak' but this has the same issue (it seems to register only if I end the last word with a period or space before pressing enter).

Here's a sandbox where I've setup this scenario: https://playcode.io/1262618

This answer suggests I could write a custom function using RegEx to check for line breaks, however given the answer is 7 years old I'm wondering if there's now a more straightforward way to do this.


Solution

  • This will do the work

    
    function newEnterHandler(callback) {
      let countEnter = 0;
      return event => {
        const newCount = (event.target.value.match(/\n/g) || []).length;
        if (countEnter < newCount) callback(event);
        countEnter = newCount;
      }
    }
    
    const textarea = document.querySelector('textarea');
    
    const handler = newEnterHandler((event) => {
      console.log("Enter pressed");
      console.log("Current Value:\n", event.target.value);
      //
      // Your Code Here
      //
    });
    
    textarea.addEventListener('input', handler);