Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is touchstart event after click?

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/

like image 628
NoBugs Avatar asked Jun 17 '15 02:06

NoBugs


People also ask

How do you bind Touchstart and click events but not respond to both?

Use of the preventDefault() or stopPropagation() method: This method prevents the event handler from responding to both touchstart and clicks events.

What is Touchstart click?

The touchstart event occurs when the user touches an element. Note: The touchstart event will only work on devices with a touch screen. Tip: Other events related to the touchstart event are: touchend - occurs when the user removes the finger from an element.

What is Touchstart event in Javascript?

The touchstart event is used to execute a script whenever the user touches an HTML element. On touching a particular element, if the touchstart event is associated with it, it can be used to trigger a javascript function. Note: The touchstart event works only on touch screen devices.

Does touch trigger click event?

Because mobile browsers should also work with with web applications that were build for mouse devices, touch devices also fire classic mouse events like mousedown or click . When a user follows a link on a touch device, the following events will be fired in sequence: touchstart. touchend.


1 Answers

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!

like image 92
Benjamin Solum Avatar answered Oct 03 '22 00:10

Benjamin Solum