keypress event is not running on a mobile device

心已入冬 提交于 2019-12-25 09:34:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/45270828/keypress-event-is-not-running-on-a-mobile-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!