0

I need to add a certain kind of support for touch devices on a current project. As this is the first time I have to do something like this, I took a look at the code of some "well made" websites to see how they do that.

One page does something like this:

if(document.querySelectorAll && (navigator.platform == "iPad" || navigator.platform.substring(0, 6) == "iPhone" || navigator.platform == "iPod" || navigator.userAgent.indexOf('Android') > -1)) {...}

I tested it on all the devices I have at hand and it works, but please tell me, is it alright to do it this way? Is there a "correct" way to do it?

I am asking because here I've read that browser detection should be avoided, instead object detection should be used. Now I see that they are also testing for document.querySelectorAll which is object detection, so maybe everything that comes after it is just some sort of safety net?

2 Answers 2

1

Browser detection should be avoided, yes. Because a browser can change.

Today, maybe google Chrome don't support a feature. But tomorrow Chrome should be updated and support it.

So if you do something like if (!isGoogleChrome()), the day when Chrome is updated, you must update your code.

You should do object detection. For example, if you want to make sure that a function/object is here, just test it :

if (document.querySelectorAll !== undefined) {
    //...
}

You could also use http://modernizr.com/ , it can detect the current browser features for you.

1
  • The problem here is: Modernizr can't detect if the device has a touch screen.
    – Sven
    Mar 7, 2013 at 7:52
0

The code you use is very very sensible : any simple character insertion at the start would make it fail.

You could replace it with something like

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|Mini/i.test(navigator.userAgent)) { ...

But you should be aware that detecting devices is dangerous as they might be more diverse that what one thinks : some have better CPU, network access or screen than some desktop browsers. So for most uses, it's better to detect the features you need.

This detection can legitimately, in my opinion, be used to detect touch screens if you plan to maintain your site depending on available devices but there are other solutions, for example libraries like Modernizr or specific tests.

1
  • Good call on that last link. Feature detection is better than browser sniffing IMO for reasons above, but that last link is a good example of why and how to test for specific features.
    – Phix
    Mar 7, 2013 at 8:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.