简体   繁体   中英

Touch event not working on touch screen laptop

I have put simple code for touch event and its working fine in mobile devices but does not working in the touch screen laptop.

$(document).ready(function(){
    $(".navigation a").bind("touchstart",function(e){
      alert('Touch start!');
    });
});

Maybe is listening mouse events. You can add a variable for your event, and check if its capabilities can reproduce touch events or not. You can use modernizr javascript library to get more accuracy in this task.

http://modernizr.com/

Let me show you an example:

 var clickEvent = undefined;
 if (Modernizr.touch) { 
      clickEvent = "touchstart";
 } else {
      clickEvent = "click";
 }
 $(document).ready(function(){
    $(".navigation a").bind(clickEvent,function(e){
       alert('It works!')
    });
 });

Update: Check out the jQuery Pointer Events Polyfill project which allows you to bind to "pointer" events instead of choosing between mouse & touch. https://github.com/jquery/PEP

Bind to both, but make a flag so the function only fires once per 100ms or so.

var flag = false;
 $thing.bind('touchstart click', function(){
  if (!flag) {
    flag = true;
   setTimeout(function(){ flag = false; }, 100);
// do something
  }

  return false
});

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