views:

264

answers:

4

Is there a solid way to detect whether or not a user is using a mobile/handheld device in jQuery? Something similar to the css media attribute? I would like to run a different script if the browser is on a handheld device.

The jQuery $.browser function is not what I am looking for.

A: 

It's not jQuery, but I found this: http://detectmobilebrowser.com/

It provides scripts to detect mobile browsers in several languages, one of which is javascript. That may help you with what you're looking for.

However, since you are using jQuery, you might want to be aware of the jQuery.support collection. It's a collection of properties for detecting the capabilities of the current browser. Documentation is here: http://api.jquery.com/jQuery.support/

Since I don't know what exactly what you're trying to accomplish, I don't know which of these will be the most useful.

All that being said, I think your best bet is to either redirect or write a different script to the output using a server-side language (if that is an option). Since you don't really know the capabilities of a mobile browser x, doing the detection and alteration logic on the server side would be the most reliable method. Of course, all of that is a moot point if you can't use a server side language :)

Ender
+1  A: 

What you are doing by wanting to detect a mobile device is getting a little too close to a "browser sniffing" concept IMO. It would likely be much better to do some feature detection. Libraries like http://www.modernizr.com/ can help with that.

For example, where is the line between mobile and non-mobile? It gets more and more blurry every day.

Bart
+1  A: 

If you're not particularly worried about small displays you could use width/height detection. So that way if width is under a certain size, the mobile site is thrown up. It may not be the perfect way, but it will probably be the easiest to detect for multiple devices. You may need to put in a specific one for the iPhone 4 (large resolution).

MoDFoX
+1  A: 

Instead of using jquery you can use simple javascript to detect it:

if( navigator.userAgent.match(/Android/i) ||
 navigator.userAgent.match(/webOS/i) ||
 navigator.userAgent.match(/iPhone/i) ||
 navigator.userAgent.match(/iPod/i)
 ){
 // some code
}
Meryl