Archive

Posts Tagged ‘iphone’

iPhone and/or iPod user agent detection with JavaScript

September 8th, 2010 1 comment

A colleague of mine sent me a piece of code which he had implemented to detect the iPhone by javascript. His code looked like this:

if((!navigator.userAgent.match(/iPhone/i))) { //step here if not iphone }

Although the code works, there is some room for improvement. And so here is what he is now using:

var agent = navigator.userAgent;
var is_iphone = (agent.match(/iPhone/i) ? true : (agent.match(/iPod/i) ? true : false));

/* the is_iphone variable is now true or false
   we can use it as many times as we like: */

if (is_iphone) {
  /* it's an iphone, do something */
}

if (!is_iphone) {
  /* this is not an iphone, do something else */
}

Much more readable too, I think.

Categories: All, Web