Fred J.
Fred J.

Reputation: 6039

keypress fail to work on mobile browser

This Meteor client event works fine on desktop browser but fail to do the same on mobile browser "Chrome".

It detects the key entry of "g" after "@" and replace it with "@gmail.com".
Any idea how to get it to work on mobile phone as well? thx

Template.input.events({
  'keypress input': function (evt, template) {
    if (evt.which === 13) {
      //do stuff
    }
    else if (Session.get('taskSelected') === 'walk') {
      if (evt.which == 103) { // "g" has been typed do gmail.com
        utility.inputReplaceWith('gmail.com', evt);
      }
      else if (evt.which === 121) {  // "y" for yahoo.com
        utility.inputReplaceWith('yahoo.com', evt);
      }
      else if (evt.which === 104) {
        utility.inputReplaceWith('hotmail.com', evt);
      }
    }
  }
});

    inputReplaceWith: (text, evt) => {
      let elem = document.getElementsByName('email')[0].value;
      if (elem.slice(-1) == '@') { // last char is "@"
        evt.preventDefault();
        document.getElementsByName('email')[0].value = elem + text;
      }
    },

Upvotes: 1

Views: 7956

Answers (2)

reyiyo
reyiyo

Reputation: 593

There is a textInput event that gives you the entered character and is also cancellable

const inputField = document.getElementById('wanted-input-field');

inputField.addEventListener('textInput', function(e) {
    // e.data will be the 1:1 input you done
    const char = e.data; // In our example = "a"

    // If you want the keyCode..
    const keyCode = char.charCodeAt(0); // a = 97

    // Stop processing if "a" is pressed
    if (keyCode === 97) {
        e.preventDefault();
        return false;
    }
    return true;
});

Upvotes: 1

ghybs
ghybs

Reputation: 53290

Looks like "keypress" event in Chrome for Android is troublesome.

See:

TL;DR: use "keydown" and/or "keyup" event(s) instead, or even "input" event.

Upvotes: 1

Related Questions