ChatGPT解决这个技术问题 Extra ChatGPT

Eliminate 300ms delay on click events in mobile Safari

I've read that mobile Safari has a 300ms delay on click events from the time the link/button is clicked to the time the event fires. The reason for the delay is to wait to see if the user intends to double-click, but from a UX perspective waiting 300ms is often undesirable.

One solution to eliminate this 300ms delay is to use jQuery Mobile "tap" handling. Unfortunately I'm not familiar with this framework and don't want to load some big framework if all I need is a line or two of code applying touchend in the right way.

Like many sites, my site has many click events like this:

$("button.submitBtn").on('click', function (e) {   
  $.ajaxSubmit({... //ajax form submisssion
});

$("a.ajax").on('click', function (e) {   
  $.ajax({... //ajax page loading
});

$("button.modal").on('click', function (e) {   
      //show/hide modal dialog
});

and what I'd like to do is to get rid of the 300ms delay on ALL those click events using a single code snippet like this:

$("a, button").on('tap', function (e) {
 $(this).trigger('click');
 e.preventDefault();
});

Is that a bad/good idea?

@Pointy thanks, this might just work...
"...obviously this isn't great from a UX perspective." I would be wary about this assumption.
@OliverMoran, thanks for the correction, i just edited that sentence, see the question above..

r
robocat

Now some mobile browsers eliminate 300 ms click delay if you set the viewport. You don't need to use workarounds anymore.

<meta name="viewport" content="width=device-width, user-scalable=no">

This is currently supported Chrome for Android, Firefox for Android and Safari for iOS

However on iOS Safari, double-tap is a scroll gesture on unzoomable pages. For that reason they can't remove the 300ms delay. If they can't remove the delay on unzoomable pages, they're unlikely to remove it on zoomable pages.

Windows Phones also retain the 300ms delay on unzoomable pages, but they don't have an alternative gesture like iOS so it's possible for them to remove this delay as Chrome has. You can remove the delay on Windows Phone using:

html {
-ms-touch-action: manipulation;
touch-action: manipulation;
}

Source: http://updates.html5rocks.com/2013/12/300ms-tap-delay-gone-away

UPDATE 2015 December

Until now, WebKit and Safari on iOS had a 350ms delay before single taps activate links or buttons to allow people to zoom into pages with a double tap. Chrome changed this a couple of months ago already by using a smarter algorithm to detect that and WebKit will follow with a similar approach. The article gives some great insights how browsers work with touch gestures and how browsers can still get so much smarter than they are today.

UPDATE 2016 March

On Safari for iOS, the 350 ms wait time to detect a second tap has been removed to create a “fast-tap” response. This is enabled for pages that declare a viewport with either width=device-width or user-scalable=no. Authors can also opt in to fast-tap behavior on specific elements by using the CSS touch-action: manipulation as documented here (scroll down to the 'Styling Fast-Tap Behavior' heading) and here.


Actually, there are touch events for WP: stackoverflow.com/questions/13396297/…
Yes which is controlled by -ms-touch-action as I wrote in my post.
Issue still exists on iOS when running the application from the home page (standalone). If anybody has found a decent workaround for it, it would be very much welcome
Setting the touch-action values to manipulation comes closest to the desired performance, but as @MiguelGuardo stated previously, the effect is lost once you add the webpage to your home screen in iOS as a standalone app.
May be someone can hack UIWebView - stackoverflow.com/questions/55155560/…
J
Jonathan

This plugin -FastClick developed by Financial Times does it perfectly for you!

Make sure though to add event.stopPropagation(); and/or event.preventDefault(); directly after the click function, otherwise it might run twice as it did for me, i.e.:

$("#buttonId").on('click',function(event){
    event.stopPropagation(); event.preventDefault();
   //do your magic

});

This is not perfect if you are using jquery mobile (version 1.3.2 anyway), it breaks the closing of the panel widget github.com/jquery/jquery-mobile/issues/6440
that event.stopPropagation() is exactly why I came to this page in the first place. Works perfectly, thank you!
@Jonathan fastclick does its magic only on touch devices which have a delay problem (else it's automatically bypassed ). However, simply adding stopPropagation & preventDefault after every click event might have unwanted side affect on all event handlers in all browsers.
M
Michael Turnwall

i know this is old but can't you just test to see if "touch" is supported in the browser? Then create a variable that's either "touchend" or "click" and use that variable as the event that gets bound to your element?

var clickOrTouch = (('ontouchend' in window)) ? 'touchend' : 'click';
$('#element').on(clickOrTouch, function() {
    // do something
});

So that code sample checks to see if the "touchend" event is supported in the browser and if not then we use the "click" event.

(Edit: changed "touchend" to "ontouchend")


Thanks, I like the simplicity of this. I would love for others to chime on its possible pitfalls.
touchend event can't replace click event because of what @Andreas Köberle explains in his reply. Like for example if you scroll and your finger stop on a button, it will trigger the link...
This is an awesome light-weight solution without having to include a big fat additional library of stuff just to get rid of the delay. Wish I could up vote 5 times on this one! (as long as you're not worried about the scroll scenario!)
For computers/browsers with touch and click event support, this is a bad solution.
Some devices support both touch and click events, and you want them both to fire in different situations. We have experienced situations where some windows or android tablets that have a mouse will obviously fire a click event when you click on a thing, but it will also fire touch events when you tap. This meant you had to listen to both events. As an additional complicating factor, some devices would synthesize a click event when you tapped, so listening to both on those devices could result in your event handler firing twice, unless you were careful.
t
tim peterson

I've come across a hugely popular alternative called Hammer.js (Github page) which I think is the best approach.

Hammer.js is a more full-featured touch library (has many swipe commands) than Fastclick.js (most upvoted answer).

Beware though: scrolling fast on mobile devices tends to really lock up the UI when you use either Hammer.js or Fastclick.js. This is a major problem if your site has a newsfeed or an interface where users will be scrolling a lot (would seem like most web apps). For this reason, I'm using neither of these plugins at the moment.


Don't use Hammerjs. It has some seriously issues, for example: github.com/EightMedia/hammer.js/issues/388 github.com/EightMedia/hammer.js/issues/366 At least don't use it until they get fixed
C
Community

Somehow, disabling zoom seems to disable this small delay. Makes sense, as double-tap isn't needed anymore then.

How can I "disable" zoom on a mobile web page?

But please be aware of the usability impact this will have. It may be useful for webpages designed as apps, but shouldn't be used for more general-purpose 'static' pages IMHO. I use it for a pet project that needs low latency.


A
Andreas Köberle

Unfortunately there is no easy way to do this. So just using touchstart or touchend will leave you with other problems like someone starts scrolling when click on on a button for example. We use zepto for a while, and even with this really good framework there are some issues that came up over the time. A lot of them are closed, but it seems is not a field of simple solution.

We have this solution to globally handle clicks on links:

   $(document.body).
    on('tap', 'a',function (e) {
      var href = this.getAttribute('href');
      if (e.defaultPrevented || !href) { return; }
      e.preventDefault();
      location.href= href;
    }).
    on('click', 'a', function (e) {
      e.preventDefault();
    });

-@Andreas, thanks so you'd advocate not using the general tap solution i posted and factoring the tap events on an element-by-element basis?
No thats not the point. The point is not to try to build a tapsolution by yourself. I'll will update my answer.
-@Andreas, thanks for your answer, many click events are AJAX so the default event is already prevented. Would you mind updating your answer to handle this too? It would seem that my general tap solution would look the same as yours in this case?
J
Jarda Pavlíček

I searched for an easy way without jquery and without fastclick library. This works for me:

var keyboard = document.getElementById("keyboard");
var buttons = keyboard.children;
var isTouch = ("ontouchstart" in window);
for (var i=0;i<buttons.length;i++) {
    if ( isTouch ) {
        buttons[i].addEventListener('touchstart', clickHandler, false);         
    } else {
        buttons[i].addEventListener('click', clickHandler, false);          
    }
}

B
Benjamin

In jQuery you can bind "touchend" event, witch trigger code inmediatly after tap (is like a keydown in keyboard). Tested on current Chrome and Firefox tablet versions. Don't forget "click" also, for your touch screen laptops and desktop devices.

jQuery('.yourElements').bind('click touchend',function(event){ event.stopPropagation(); event.preventDefault(); // everything else });


d
dz902

Just to provide some extra information.

On iOS 10, <button>s on my page could not be triggered continuously. There was always a lag.

I tried fastclick / Hammer / tapjs / replacing click with touchstart, all failed.

UPDATE: the reason seems to be that the button is too close to the edge! move it to near the center and lag gone!


B
Bruno Andrade

You're supposed to explicitly declare passive mode :

window.addEventListener('touchstart', (e) => {

    alert('fast touch');

}, { passive : true});