Is there a solid way to detect whether or not a user is using a mobile 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.
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 :)
You can't rely on
navigator.userAgent
, not every device reveals its real OS. On my HTC for example, it depends on the settings ("using mobile version" on/off). On http://my.clockodo.com, we simply usedscreen.width
to detect small devices. Unfortunately, in some Android versions there's a bug with screen.width. You can combine this way with the userAgent:In one line of javascript:
If the user agent contains 'Mobi' (as per MDN) and ontouchstart is available then it is likely to be a mobile device.
Simple function based on http://detectmobilebrowser.com/
I advise you check out http://wurfl.io/
In a nutshell, if you import a tiny JavaScript file:
You will be left with a JSON object that looks like:
(That's assuming you are using a Nexus 7, of course) and you will be able to do things like:
This is what you are looking for.
Disclaimer: I work for the company that offers this free service.
Found a solution in: http://www.abeautifulsite.net/blog/2011/11/detecting-mobile-devices-with-javascript/.
And then to verify if its a Mobile, you can test using: