Thursday, August 14, 2014

jQuery/JavaScript detect if browser is mobile (uses touch)

The following jQuery code allows you to detect if the browser is running on a touch device (for Apple iOS, Android, and even Windows phones/tablets). Other solutions I have seen often forget to take into account Windows devices, which while uncommon, it is important to not leave them with a bad user experience.
var TouchDevice = ('ontouchstart' in window) || (window.DocumentTouch) || navigator.userAgent.match(/Touch/i) == "Touch";
Once you detect if they use a touch device, you can then run your code based on that. One example is to assign a special CSS class for touch device which can be used to handle hovers differently (ie do something else instead of hover) on touch devices.

No comments:

Post a Comment