10+ useful code snippets to develop iPhone friendly websites

by Jean.

When developing websites, you have to care about different browsers, as well as mobile devices such as iPhones or iPods. In this article, let’s have a look at the 10+ most useful code snippets (Javascript, PHP, CSS, etc) for developing iPhone friendly websites, quickly and efficiently.

Detect iPhones and iPods using Javascript

When developing for the iPhone and the iPod Touch, the first thing we have to do is obviously detect it, so we can apply specific code or styles to it. The following code snippets will detect iPhones and iPods using Javascript, and redirect those users to an iPhone specific page.

if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
    if (document.cookie.indexOf("iphone_redirect=false") == -1) {
        window.location = "http://m.espn.go.com/wireless/?iphone&i=COMR";

Source: http://davidwalsh.name/detect-iphone

Detect iPhones and iPods using PHP

Although the previous snippet works great, Javascript can be disabled on the iPhone. For this reason, you may prefer to use PHP in order to detect iPhones and iPods touch.

if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone') || strstr($_SERVER['HTTP_USER_AGENT'],'iPod')) {
    header('Location: http://yoursite.com/iphone');

Source: http://davidwalsh.name/detect-iphone

Set iPhone width as the viewport

How many times did you load a website in your iPhone and it just looked like a thumbnail? The reason of this is that the developer forgot to define the viewport (or didn’t know it existed). The width=device-width statement allows you to define the document width as being the same than the width of the iPhone screen. The two other statements are preventing the page from being scaled, which is useful if you’re developing an iPhone-only website. Otherwise, you can remove those statements.
Defining a viewport is easy: Just insert the following meta in the head section of your html document.

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">

Source: http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/

Insert an iPhone specific icon

When a user adds your page to the home screen, the iPhone will automatically use a screenshot of your website as an icon. But you can provide your own icon, which is definitely better.
Defining a custom iPhone icon is easy: Simply paste the following in the head section of your html document. The image should be 57px by 57px in .png format. You do not need to add the shine or corners, as the iPhone will do that for you automatically.

<rel="apple-touch-icon" href="images/template/engage.png"/>

Source: http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/

Prevent Safari from adjusting text size on rotate

When you rotate the iPhone, Safari adjust text size. If for some reason you’d like to prevent this effect, simply use the following CSS declaration. It has to be inserted in your CSS file.
The -webkit-text-size-adjust is a webkit-only CSS property that allow you to control text adjustment.

html, body, form, fieldset, p, div, h1, h2, h3, h4, h5, h6 {

Source: http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/

Detect iPhone orientation

Due to the fact that the iPhone allow its users to view a page in both portrait and landscape modes, you may need to be able to detect in which mode the document is being read.
This handy javascript function will detect the current iPhone orientation and will apply a specific CSS class so you can style it your way. Note that in this example, the CSS class is added to the page_wrapper ID. Replace it by the desired ID name (See line 24).

window.onload = function initialLoad() {

function updateOrientation(){
    var contentType = "show_";
        case 0:
	contentType += "normal";

	case -90:
	contentType += "right";

	case 90:
	contentType += "left";

	case 180:
	contentType += "flipped";
    document.getElementById("page_wrapper").setAttribute("class", contentType);

Source: http://www.engageinteractive.co.uk/blog/2008/06/19/tutorial-building-a-website-for-the-iphone/

Apply CSS styles to iPhones/iPods only

Browser sniffing can be useful, but for many reasons it isn’t the best practice to detect a browser. If you’re looking for a cleaner way to apply CSS styles to the iPhone only, you should use th following. It has to be pasted on your regular CSS file.

@media screen and (max-device-width: 480px){
    /* All iPhone only CSS goes here */

Source: http://csswizardry.com/2010/01/iphone-css-tips-for-building-iphone-websites/

Automatically re-size images for iPhones

On recent websites, most images are above 480 pixels wide. Due to the iPhone small size, there’s a strong chance that images will break out of the wrapper area.
Using the following CSS code, you’ll be able to automatically re-size the website images to 100%. As the device max width is 480px, images will never be wider.

@media screen and (max-device-width: 480px){

Source: http://csswizardry.com/2010/01/iphone-css-tips-for-building-iphone-websites/

Hide toolbar by default

On a small screen such as the iPhone screen, a toolbar is useful but also wastes a lot of space. If you’d like to hide Safari toolbar by default when an iPhone visitor open your website, just implement the following javascript code.

window.addEventListener('load', function() {
    setTimeout(scrollTo, 0, 0, 1);
}, false);

Source: http://articles.sitepoint.com/article/iphone-development-12-tips/2

Make use of special links

Do you remember those “mailto” link that were very popular some years ago? This prefix automatically open the default email client used by the person who clicked on it. The iPhone has introduced two similar prefixes, tel and sms, which allows the person who clicked on it to phone or text automatically.
I’m definitely not a fan of those, but maybe that will be useful to you. The only thing you have to do to implement this, is to paste the following anywhere on your html page.

<a href="tel:12345678900">Call me</a>
<a href="sms:12345678900">Send me a text</a>

Source: http://articles.sitepoint.com/article/iphone-development-12-tips/3

Simulate :hover pseudo class

As no one is using a mouse on the iPhone, the :hover CSS pseudo class isn’t used. Though, using some Javascript you can simulate the :hover pseudo class when the user will have his finger on a link.

var myLinks = document.getElementsByTagName('a');
for(var i = 0; i < myLinks.length; i++){
   myLinks[i].addEventListener('touchstart', function(){this.className = "hover";}, false);
   myLinks[i].addEventListener('touchend', function(){this.className = "";}, false);

Once you added the code above to your document, you can start css styling:

a:hover, a.hover {
    /* whatever your hover effect is */

Source: http://www.evotech.net/blog/2008/12/hover-pseudoclass-for-the-iphone/

CWC Special Deal!

Get one year of quality hosting + domain from A Small Orange for only $40 with our exclusive deal!

Featured WordPress Theme

Bridge - Creative Multi purpose WordPress theme

  • Pingback: uberVU - social comments()

    • http://bringmebusiness.com.au John

      The viewport tag doesn’t work on iPhone. It never works. Only way is lengthy stupidly longwinded javascript. Sorry, anyone who’s thinking this will fix your viewport issues, it will never do that. Tried and tested.

  • http://www.evolvesolutions.com Douglas Kelly

    Dude I have to say that you always have something I want to know. Nice job on this one. I’m definitely going to link over here in my next blog post.

    Keep up the GREAT work.

  • http://gesf.org gesf

    Thanks a lot for the hint 😉

  • http://www.eclipsedesign.eu/ Kartlos Tchavelachvili

    Very cool snippets! thanks

  • http://loneplacebo.com Tony

    Would this be like not using the WPTouch iPhone theme plugin?

  • http://www.mo-money.de/blog Frank

    Thank JB!!! Do you plan a similar article for Android as well? Or can we easily transfer the snippets into android ones?


    • http://www.wprecipes.com Jean-Baptiste Jung

      A similar post about Android is definitely a great idea :) Thanks for the inspiration!

      • http://www.mo-money.de/blog Frank

        Jaaa – not a copy of course. Lets say I would be happy to read an article about Android as well.

        Best regards!

  • http://www.amasso.info Antoni Massó Mola

    This is also a useful iPhone code to turn off scrolling (bounces)

    document.ontouchmove = function(event){

  • Pingback: === popurls.com === popular today()

  • http://www.cheaphoteldealsaustralia.com Metric Stormtrooper

    there is an iphone browser emulator @ http://iphonetester.com in case you don’t have one but want to check your sites anyway.

    • Jakob E

      Don’ use the iPhone emulator (iphonetester.com) it does not act as mobile safari
      and it takes flash too 😉

  • http://www.insidethewebb.com/ Inside the Webb

    I didn’t even know you could do all of this with JavaScript! I’ll have to figure out a way to design a mobile template for my site, it’ll be awesome to showcase my blog directly on mobile phones.

  • Pingback: 10+ useful code snippets to develop iPhone friendly websites | Dev Loom()

  • Pingback: 10 användbara kodsnuttar till iPhone-anpassade sajter | Teknikveckan()

  • http://xantiz.com/ Xanti SS

    You should note that using strstr (PHP function) to find if a particular string is inside another is not recommended, and that the function strpos should be used instead.


  • http://guru.gurbir.at Alexander Taubenkorb

    Really nice work!

    Ad Insert an iPhone specific icon:
    should be

  • Pingback: Bookmarks for March 2nd from 07:23 to 07:33 | The Wahoffs.com()

  • Pingback: t3n-Linktipps: CSS-Komprimierung, CSS History Hacks, Internet-Zukunft, Code-Snippets und iPhone-Apps für Shopbetreiber » t3n News()

  • http://www.canaydogan.net Can Aydoğan

    Great snippets! Thanks.

  • http://www.blue-agate.com Minna

    Very helpful post! I did notice that for the iPhone, setting the DOCTYPE declaration as one of the mobile profiles changed the resolution initially, though I did add the viewport tag later because this is useful for many other devices. http://en.wikipedia.org/wiki/XHTML_Mobile_Profile

  • http://cssmake.ru Elena

    Thank you for interesting information. I was searching this information for a long time.

  • http://www.amberweinberg.com Amber Weinberg

    I did my first site for the iPhone a few weeks ago and it was definitely a learning experience. After I finished that site, I went back and made a few tweaks to my own to work better 😉

  • http://www.jennamolby.com Jenna Molby

    I’ve been looking for something like this for a long time, thanks.

  • http://sonnygauran.co.cc/blog Sonny Gauran

    Hmmm, I smell things needed to cook-up an iPhone plugin for something like jQuery.

    Nice roundup! +1
    Bookmarked! =)

  • http://unedible.com/ Alice

    There’s also the code that allows your site to be used as a web app, which totally removes the URL bar when launched as an app (you can also pick what color the time/carrier/battery bar is).

    • http://unedible.com/ Alice

      ugh, html filtering.
      the “apple-mobile-web-app-capable” and “apple-mobile-web-app-status-bar-style” meta tags, found here: http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html

  • Pingback: Code snippets for iphone friendly sites | web development helpdesk()

  • Joao Pereira

    Great post. Tanks for sharing this great tips.

  • http://www.jordanwalker.net Jordan Walker

    Excellent resource for developers wanting to fork display methods for mobile browsers.

  • Pingback: CSS Brigit | 10+ useful code snippets to develop iPhone friendly websites()

  • Pingback: Most Tweeted Articles by CSS Experts()

  • Pingback: Website Snippets at Under The Bridge()

  • Pingback: Sitez » links for 2010-03-04()

  • Pingback: Mes favoris du 4-03-10 au 5-03-10 » Gilles Toubiana()

  • Pingback: Bokmerke denne veka (weekly) | IKT i læring()

  • Pingback: Cheatsheet: 2010 03.01 ~ 03.07 - gOODiDEA.NET()

  • Pingback: Internet Briefing Blog / Wochenendsurf-Tour()

  • Pingback: links for 2010-03-07 « 個人的な雑記()

  • Pingback: Delicious Top Ten March 1-7 2010 Best Popular Links | DecaBot()

  • Pingback: Daily David - davidgagne.net()

  • Pingback: Prepara tu sitio para iPhone | Ayuda WordPress()

  • Pingback: Heti események | I build websites()

  • Pingback: 10+ useful code snippets to develop iPhone friendly websites - Simon Day – Professional web designer since 1997()

  • Pingback: Scripts pour détecter les mobiles | traffic-internet.net()

  • Pingback: Dentaku » 10+ useful code snippets to develop iPhone friendly websites()

  • http://www.ParrotCareBasics.com Alan Deacon

    Very helpful. Thanks a lot

  • Pingback: Rémi Garcia – Blog » Penser et optimiser son site pour les appareils mobiles()

  • http://www.danielwichers.nl/ daniel

    It think what Alexander Taubenkorb was trying to say is inserting the iPhone icon should be done like this:

    Or you can just name your icon apple-touch-icon.png and place it in your root directory.
    Nice post though!

  • Pingback: Bookmarks for March 22nd through March 24th | For My Own Amusement()

  • http://www.foundonline.co.uk freescene

    nice one, just need to get my head round it all now.


  • Pingback: 10+ regular expressions for efficient web development()

  • Pingback: March 2010 Digest | Brightscape Blog()

  • Pingback: Web Dev Tutorials 1# | Booto'Blog()

  • http://www.anxietysymptomssite.com/ Mark Slater

    Amazing post ! This would really help the web developers to easily build iPhone friendly websites. The convenience of using special links would provide ample new opportunities, ideas and creative websites for the iphone. Hoping to welcome more such useful codes in the iphone world.

  • http://www.northamptondesign.co.uk Shane

    Really great, helpful post. Can’t wait to use some of these snippets!

  • http://atvsforsaleinusa.com atvs

    Making websites for mobile phone surfing is very essential nowadays. This generation started web surfing more through iphones, ipods and other mobile devices. So have it in mind, the next generation will use mobile device more than now for Internet surfing. Make sure that your website having the capability to accept the mobile surfing access.

  • http://theneworder.net Jon

    OMG this article is full of win.

    I am going to implement this stuff right now! Thanks for the great info

  • http://www.estudiopositivo.com Estudio Positivo

    Thanks for this post!!

  • http://www.michalkopanski.com/ Michal Kopanski

    The iPhone home icon should be a ‘link’ attribute. In your code you skip the word ‘link’, and straight to rel, which doesn’t work.

  • http://anassin.com Swat Chap

    Nice post!

  • http://bestiphonedownloads.info Cody Daniels

    This info is really useful, especially for an iPhone newbie. Thanks for taking the time to publish!

  • Priyesh

    A very good post. It is very important in today’s fast paced environment to be able to view websites on your phone. Meaning that the ability to create websites for mobile viewing is essential. This post gives you a great insight into building web sites for the iphone.

    • http://www.youtube.com/watch?v=zQsMEyoo_9M Jamie

      Thanks for this very helpful post. These days site developers must always consider the iPhone users market because they’re rapidly increasing in size. I’m just wondering though if you have or plan to write a similar post but this time caters to Android or Blackberry?

  • http://mdskincareguide.blogspot.com/ JEAN

    Thank you this is very interesting but i prefer using WP touch pro !

  • http://www.chidgey.me Gareth Chidgey

    Thank you!!!! I was wondering how to get my menu’s to work right on an iPhone. Works like a dream.

  • http://www.mcsf23.com Matt

    Great post. One of the top things to look for in web design in 2011 is mobile exclusive content. This is a great start to be well on your way to staying up to date. Thanks

  • http://phoneauctions.net.au Tony

    Another piece of the puzzle is solved… Still trying to work out how to get the iPhone to display the same text sizes as normal browsers. It’s tricky!

  • http://www.niallflynn.com/ Niall Flynn

    Cheers, this is really handy :)

  • Joe

    Please, please, change the third example to

    to remove the maximum scale constraint. Web developers copy and paste examples and often don’t have time to consider accidental policy like this. Disabling scaling is extremely frustrating to people who want to scale. Scaling does not frustrate anyone capable of using an iOS device without being frustrated by it anyway.

    It is obvious that disabling this feature can only cause pain. It can never help. Please. Please. I’m begging you. I want to stab someone every time I land on a web page that thinks it knows more about user experience than the people who made Safari Mobile. They are always, always, wrong. No human being does this on purpose. They just copy some stuff they found googling around. Please make that stuff they copy more humane.

  • http://www.mike-irving.co.uk/ Mike Irving

    Great hints… I’m liking the Home Screen Icon tip… and the font resizing and bar hiding mechanisms are a must.

    The user agent is pretty much a given… you can also use some open source scripts to detect a whole array of mobile devices, client or server side, see: http://detectmobilebrowsers.com/