Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I listen for input events on mobile browsers?

I wrote a dumb little "web app" that consists of a simple text box that manipulates text and displays the output. Works as I expect on desktop, but not on mobile (Chrome and Safari on iOS). I'm simply adding an event listener to an input, but the handler doesn't seem to be getting fired. I've checked caniuse and it seems compatible, and haven't found any questions asked about this, so I'm hoping it's something I'm just overlooking in my code.

Code snippet:

const input = document.querySelector('#input'); // Yes, that's the input ID.
input.addEventListener('change', clapBack);

Link to full file:

https://github.com/martellaj/clap-back-generator/blob/master/js/main.js

like image 655
Joe Martella Avatar asked Oct 14 '25 23:10

Joe Martella


1 Answers

Instead of using event.key or event.code properties of keypress (keyup, keydown) event, I have used event.inputType and event.data properties of input (update) event and added few restricting attributes to the input tag to overcome 'smartness' of mobile keyboard app. It is an ugly hack but worked for my purpose.

HTML:

<input type="text" id="inpt" autocapitalize="none" autocomplete="off" autocorrect="off" spellcheck="false" />

JS:

var inpt = document.getElementById('inpt');
inpt.addEventListener('input', do_on_input);

function do_on_input(e) {
  
  if( e.inputType == "insertText"){
    console.log( e.data );
  }
  
  if( e.inputType == "deleteContentBackward"){
    console.log('Backspace');     
  }
  
  if( e.inputType == "insertCompositionText"){
    // without restrictive attribbutes you will need to deal with this type events
  }
  
}
like image 151
elshnkhll Avatar answered Oct 17 '25 13:10

elshnkhll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!