5

I want to perform a check in one of my JavaScript functions that determines whether I am on a smartphone and then decide whether or not to run the function based on the results.

What is the best way to detect/check for a smartphone (or handheld device in general) in JavaScript?

e.g.

if (user is on a smartphone) {
//run this code if on a phone
} else {
//run this code if not on a phone
}

If there is not one definite method to check for a phone, then what are the best selection of checks I should to perform before deciding which code to run?

EDIT/UPDATE: The answers and comments on this similar post should give me something to go on - What is the best way to detect a mobile device in jQuery?

Community
  • 1
  • 1
Dave Haigh
  • 3,919
  • 5
  • 30
  • 56
  • This might help: http://stackoverflow.com/questions/10823144/is-there-a-quintessential-mobile-user-agent-regexp-pattern – techfoobar Jun 13 '12 at 11:24
  • @ilanco thanks I couldn't find that post. I think the answers/comments on there should give me something to work with. – Dave Haigh Jun 13 '12 at 11:34
  • I think that an answer has already been provided here: https://stackoverflow.com/questions/3514784/best-way-to-detect-handheld-device-in-jquery Moderators: It would be good if an owner can close his own question. I know there is a voting system to do this...Might serve best who knows – brumScouse Jun 19 '12 at 15:42

3 Answers3

3

Ye olde browser sniffing seems to be the solution

if( navigator.userAgent.match(/Android/i)
 || navigator.userAgent.match(/webOS/i)
 || navigator.userAgent.match(/iPhone/i)
 || navigator.userAgent.match(/iPad/i)
 || navigator.userAgent.match(/iPod/i)
 || navigator.userAgent.match(/BlackBerry/i)
 ){
 // some code..
}
primavera133
  • 1,204
  • 1
  • 14
  • 22
0

You could try twitter bootstrap, http://twitter.github.com/bootstrap/scaffolding.html. In particular the Responsive design section.

Vinnyq12
  • 1,439
  • 9
  • 8
  • Bootstrap is purely CSS and no Javascript-detection. (As always) there is an ugly hack though: http://stackoverflow.com/questions/14441456/how-to-detect-which-device-view-youre-on-using-twitter-bootstrap-api – cederlof Apr 10 '13 at 13:37
0

You can use the Categorizr JS library to test whether the user's device is a mobile phone, a tablet, a smart tv or a desktop. Categorizr uses user agent sniffing, so you should keep an eye out for updates to the script, as user agents tend to "evolve" over time.

Here's how you would use Categorizr to check if the user is on a smartphone, but not a smart TV, a desktop or a tablet:

if (categorizr.isMobile) {
    //run this code if on a phone
} else {
    //run this code if not on a phone
}
kotekzot
  • 1,348
  • 1
  • 13
  • 23