简体   繁体   中英

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

the input event is not supported in mobile

https://developer.mozilla.org/en-US/docs/Web/Events/input

As @jam mok said, input isn't supported on mobile. Why not just use a change event?

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

For all humans still looking for an answer: onkeyup() does the trick.

So the solution for the mentioned code may look like:

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

Of course it can also be used inline: <input name="inputText" onkeyup="clapBack()">

Updating for 2019: input and change is supported by the majority of popular mobile browsers: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event

The following allows you to detect change on mobile browsers:

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

Here's an example: https://codepen.io/anon/pen/LwVoWa

Instead of using event . key or event . code properties of keypress (keyup, keydown) event, I have used event . inputType , event . data of 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
  }
  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM