How to detect correctly the event handler using jQuery

jQuey event handler

The event handler on touch and desktop devices

Basically the iPad, or in general touch based devices haven’t any “click” event. Instead we have a “touch” event.
How can we handle them correclty?

So the solution is simple and elegant: once detected the device we assign the correct event handler to a variable and then we can use it, without be worried about the device is on our web page.

This snippet works for the iPad, but can be easily extended to other devices or targetted to other devices.

var event = (navigator.userAgent.match(/iPad/i)) ? "touchstart" : "click";

At this point we can easily use the correct event trigger:

$('.selector').on(event, function() {
// Your code here

That’s it! :)

Lascia un Commento!