Why is touchstart event after click?

3k views Asked by At

Here's something odd, that I felt sure was working in earlier mobile browsers: In Chrome on Android, and Safari on iOS, it seems the touchstart event is fired after the click event, not before. When did this change?

A simple example:

jQuery(function($) {
    var touched = false;
    $('#clicky').on('touchstart', function(evt){
        touched = true;
        evt.preventDefault();
    })
    .click(function(){
        if (!touched) {
            alert("somehow touch didn't fire")
        }
    });
})

Run this fiddle, and you'll see the alert can pop up on Android and iOS, when it should actually never show!

http://jsfiddle.net/quxnxu7d/2/

3

There are 3 answers

0
David Bradshaw On

Have you tried using mousedown instead of click? That way you should get different events for touch and click without any double firing. You will also likely need to use keydown to keep this site accessible.

0
Benjamin Solum On

I ran it through Chrome on Android and it worked as you expected for me. I added an alert to the touchstart handler and it fired to be sure that it was firing first and it did.

Take a look at the touch events mdn article. The article specifically mentions:

calling preventDefault() on a touchstart or the first touchmove event of a series prevents the corresponding mouse events from firing

Click is a mouse event so it "should" work as you expect (and it was working for me). I'd verify that the events are indeed running out of order (use console.log() instead of alert()) on your target browsers. If they are, which is perfectly possible with less than perfect browsers/specs, try using a different mouse event like mouseup. My guess is that you'll be able to find an event that works consistently.

Good luck!

0
Monfa.red On

There is a 300ms delay between a physical tap and the firing of a click event on some mobile browsers (e.g. iOS Safari) I ran into the same issue and FastClick jQuery plugin fixed it for me

Have a look FastClick