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/
Use of the preventDefault() or stopPropagation() method: This method prevents the event handler from responding to both touchstart and clicks events.
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.
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.
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.
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 firsttouchmove
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With