简体   繁体   中英

keypress event is not running on a mobile device

the problem I am having is that the event handler isn't running when the user types on mobile devices browsers.

My javascript code working like this: When user write someting and press space javascript code automatically adding #(diez) tag for hashtag system. Like if you write: this is test message , javascript code change it like this: #this #is #test #message all after space.

If you check this DEMO on your computer browser ( Chrome, Safari, Firefox, Opera ) it is working fine.

But if you check this DEMO on your mobile browsers event handler isn't running when you types someting.

$("body").on("keypress","#text", function(e) {
     var code = e.charCode || e.keyCode || e.which;
    if (charactersX.has(code)) {
      var text = $("#text").text();
      text = addHashtags(text);
      $("#text").text(text);
      placeCaretAtEndX(document.querySelector("#text"));
      console.log(text);
    } else if (forbiddenCharactersX.has(code)) {
      e.preventDefault();
      console.log("something");
    }
  });

Full code is HERE .

I replaced the $(document).on("keypress", "#textInpu", function(){.....}) part of your code with this and the bug is gone:

   $(document).on("textInput", "#text", function(event) {
      var code = event.originalEvent.data.charCodeAt(0);
      if (charactersX.has(code)) {
         // Get and modify text.
         var text = $("#text").text();
         text = addHashtags(text);
         // Save content.
         $("#text").text(text);
         // Move cursor to the end
         placeCaretAtEndX(document.querySelector("#text"));
      } else if (forbiddenCharactersX.has(code)) {
         e.preventDefault();
      }
   });
});

This was your issue if you are wondering: keyCode on android is always 229

If there are any bugs after you replace your code with what i provided, please let me know.

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