iPhone / iPad Detection Using Javascript

Need to render something different on an iPhone/iPad to a normal computer? Here's how!

Earlier today I was updating the layout of a website and while it looked great on all modern browsers, the position of the background was way out on the iPad and iPhone.

The reason for this is that in a normal web browser, if you set your background to "center center", that's where it will put it. As a user, you will then only see what your monitor resolution allows.

Apple however decided to make their devices a little more intuitive, and the background image actually scales to fit the full image in the browser window. Normally a nice feature, not so great in this case.

Thankfully (thanks to David Walsh), it is quite easy to determine if the user is viewing your website on such devices, by using a small bit of javascript.

I simply created a function called iCheck which looks like this:

function iCheck()
{
    // For use within normal web clients 
    var isiPad = navigator.userAgent.match(/iPad/i) != null;
    var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
    var isiPod = navigator.userAgent.match(/iPod/i) != null;

    // For use within iPad developer UIWebView
    // Thanks to Andrew Hedges!
    //var ua = navigator.userAgent;
    //var isiPad = /iPad/i.test(ua) || /iPhone OS 3_1_2/i.test(ua) || /iPhone OS 3_2_2/i.test(ua) || /iPod/i.test(ua);
    
    if(isiPad || isiPhone || isiPod)
    {
        //perform device specific code here
    }
}

Then in the body tag, added it to onLoad.

<body onload="iCheck();">

Worked a treat and I will definitely be using this for future projects as well!