Search code examples
javascriptjquerywindowsgoogle-chrometouch

Google Chrome - is this a BUG? Javascript issue? Touchscreen inputs are not working


I have this simple button. It works on the same machine with a USB mouse click, but does not work when tapped via touchscreen (Iiyama touchscreen).

<script>
function button_vipanytime() {
  console.log('OK we clicked');
  alert('Touch screen works');// using mouse I get the alert, but when I tap with touchscreen it never executes.

}

/* fail too
$(document).ready(function() {
  $('#vip_anytime').click(function() { 
    alert('jquery');  
  });
});
*/
</script>

<div id="vip_anytime" style="" onclick="button_vipanytime(); " >
    <img src="images/sp/vip.png"  style="width:70px; height: 48px;" />
</div>

How can i make it compatible with touch input?


Solution

  • As screen touching is supported by another set of events, you should add listeners for touch-based events. Try this:

    $("#vip_anytime").on("touchend", function(e){
     alert("OK we touched");
    });
    

    This should not replace the normal "click" event, but be added alongside it.

    $("#vip_anytime").on("click touchend", function(e){
       alert("OK we touched");
    });
    

    If you require more information, then you might find this helpful: https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html

    Edit:

    Native JavaScript implementation might go as follows:

    document.getElementById("vip_anytime").addEventListener("touchend", function(e) {
      alert("OK we touched");
    });
    

    And lastly, though it is not best practice you might call it by directly in your HTML code, as in your code example:

    <div id="vip_anytime" ontouchend="button_vipanytime();">click me</div>