简体   繁体   中英

How do I get touch events without big library

I am using jquery, but I don't want to use jquery mobile, because it is so large, and I don't think I need it. All I am trying to do is get a touch event. This is what I've got.

 $('#menuButton').on('click touchstart', function(){
  $('#menu').toggleClass('block')
 });

It only kind-of works, but seems to be firing twice a lot on my phone. I think I should check for both touchstart and touchend somehow. This needs to work on all types of devices, hopefully. Thanks!

Behold! The lifecycle of a touch:

  1. your finger hits the glass -> touchstart!
  2. your finger leaves the glass -> touchend!
  3. your finger it lingers -> click!

Now the lifecycle of a mouse click:

  1. your finger depresses the button -> mousedown!
  2. your finger it removes pressure from the button -> mouseup!
  3. your finger it lingers -> click!

If you are listening for both touchstart and click, the event will fire once on mouse or trackpad computers, and twice on touch devices as you are listening for 2 events in the lifecycle.

If you really want to use click for desktops and touchstart of touch devices (a good idea in many cases), you can do something like this:

 var clickEvent = (isMobile)?'touchstart':'click';
 $('#menuButton').on(clickEvent, function(){
   $('#menu').toggleClass('block')
 });

How you go about finding isMobile is another story.


update : I've written a handy script for detecting mobile, if your interested its npm isMobile

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