Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check browser for touchstart support using JS/jQuery?

In an attempt to follow best practices, we're trying to use the proper JavaScript/jQuery events according to what device you are using. For example, we're building a mobile site that has an tag that will have an onclick or touch event. In the case of an iPhone, we'd like to use the "touchstart" event. We'd like to test if their device supports "touchstart" before we bind that handler to the object. If it doesn't, then we will bind "onclick" instead.

What is the best way to do this?

like image 802
Alex Avatar asked May 26 '10 18:05

Alex


3 Answers

You can detect if the event is supported by:

if ('ontouchstart' in document.documentElement) {
  //...
}

Give a look to this article:

  • Detecting event support without browser sniffing

The isEventSupported function published there, is really good at detecting a wide variety of events, and it's cross-browser.

like image 117
Christian C. Salvadó Avatar answered Sep 21 '22 23:09

Christian C. Salvadó


Use this code to detect if the device supports touch.

Also work for windows 8 IE10 which uses 'MSPointerDown' event instead of 'touchmove'

var supportsTouch = false;
if ('ontouchstart' in window) {
    //iOS & android
    supportsTouch = true;

} else if(window.navigator.msPointerEnabled) {

    // Windows
    // To test for touch capable hardware 
    if(navigator.msMaxTouchPoints) {
        supportsTouch = true;
    }

}
like image 36
George Filippakos Avatar answered Sep 22 '22 23:09

George Filippakos


You could check if typeof document.body.ontouchstart == "undefined" to fall back to normal dom events

like image 32
antimatter15 Avatar answered Sep 19 '22 23:09

antimatter15