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');
    exit();
}

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 {
    -webkit-text-size-adjust:none;
}

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() {
    updateOrientation();
}

function updateOrientation(){
    var contentType = "show_";
    switch(window.orientation){
        case 0:
	contentType += "normal";
	break;

	case -90:
	contentType += "right";
	break;

	case 90:
	contentType += "left";
	break;

	case 180:
	contentType += "flipped";
	break;
    }
    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){
    img{
        max-width:100%;
        height:auto;
    }
}

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/

 

35 Comments

  1. Posted March 1, 2010 at 11:13 am | Permalink

    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.
    dk
    @mollask

  2. Posted March 1, 2010 at 11:49 am | Permalink

    Thanks a lot for the hint ;)

  3. Posted March 1, 2010 at 1:48 pm | Permalink

    Very cool snippets! thanks

  4. Posted March 1, 2010 at 1:50 pm | Permalink

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

  5. Posted March 1, 2010 at 1:50 pm | Permalink

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

    Greetings!

    • Posted March 1, 2010 at 1:53 pm | Permalink

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

      • Posted March 1, 2010 at 3:39 pm | Permalink

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

        Best regards!

  6. Posted March 1, 2010 at 2:23 pm | Permalink

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

    document.ontouchmove = function(event){
    event.preventDefault();
    }

  7. Posted March 1, 2010 at 4:34 pm | Permalink

    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
      Posted May 16, 2010 at 6:46 pm | Permalink

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

  8. Posted March 1, 2010 at 10:59 pm | Permalink

    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.

  9. Posted March 2, 2010 at 8:53 am | Permalink

    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://php.net/strstr

  10. Posted March 2, 2010 at 9:27 am | Permalink

    Really nice work!

    Ad Insert an iPhone specific icon:
    should be

  11. Posted March 2, 2010 at 10:15 am | Permalink

    Great snippets! Thanks.

  12. Posted March 2, 2010 at 1:41 pm | Permalink

    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

  13. Posted March 2, 2010 at 3:25 pm | Permalink

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

  14. Posted March 2, 2010 at 4:49 pm | Permalink

    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 ;)

  15. Posted March 2, 2010 at 6:50 pm | Permalink

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

  16. Posted March 2, 2010 at 8:21 pm | Permalink

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

    Nice roundup! +1
    Bookmarked! =)

  17. Posted March 2, 2010 at 10:43 pm | Permalink

    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).

  18. Joao Pereira
    Posted March 3, 2010 at 9:40 am | Permalink

    Great post. Tanks for sharing this great tips.

  19. Posted March 3, 2010 at 11:20 am | Permalink

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

  20. Posted March 16, 2010 at 1:00 am | Permalink

    Very helpful. Thanks a lot

  21. Posted March 18, 2010 at 11:47 am | Permalink

    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!

  22. Posted March 23, 2010 at 3:58 am | Permalink

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

    :D

  23. Posted April 9, 2010 at 6:32 am | Permalink

    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.

  24. Posted April 30, 2010 at 6:19 am | Permalink

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

  25. Posted May 6, 2010 at 6:25 am | Permalink

    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.

  26. Posted June 11, 2010 at 1:06 pm | Permalink

    OMG this article is full of win.

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

  27. Posted June 21, 2010 at 7:27 pm | Permalink

    Thanks for this post!!

  28. Posted July 10, 2010 at 5:05 am | Permalink

    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.

  29. Posted July 14, 2010 at 2:29 pm | Permalink

    Nice post!

  30. Posted July 17, 2010 at 5:23 pm | Permalink

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

  31. Priyesh
    Posted July 20, 2010 at 4:21 am | Permalink

    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.

28 Trackbacks

  1. By uberVU - social comments on March 1, 2010 at 11:12 am

    Social comments and analytics for this post…

    This post was mentioned on Twitter by SergioArantes: 10+ useful code snippets to develop iPhone friendly websites http://bit.ly/9qHxmC…

  2. By === popurls.com === popular today on March 1, 2010 at 2:40 pm

    === popurls.com === popular today…

    yeah! this story has entered the popular today section on popurls.com…

  3. [...] 10+ useful code snippets to develop iPhone friendly websites Via / @jlantunez [...]

  4. [...] Who Code – 10+ Useful Code Snippets To Develop IPhone Friendly Websites Relaterade inlägg:85 riktigt snygga FlashsajterBygg en iPhone-anpassad websiteThings i din [...]

  5. [...] 10+ useful code snippets to develop iPhone friendly websites – [...]

  6. [...] Moderne Webseiten lassen sich heute nicht mehr nur mit diversen Browsern konrekt anzeigen, sondern sie sind auch für den mobilen Zugriff optimiert. Jean-Baptiste Jung zeigt dazu nützliche Code-Snippets zur Entwicklung von iPhone-freundlichen Websites. [...]

  7. [...] across “10+ Useful Code Snippets To Develop IPhone Friendly Websites” at catswhocode.com and thought it worth sharing with [...]

  8. 10+ useful code snippets to develop iPhone friendly websites…

    When developing websites, you have to care about different browsers, as well as mobile devices such as iPhones or iPods.

  9. By Most Tweeted Articles by CSS Experts on March 3, 2010 at 9:08 pm

    [...] the topic of Web Design is home to many debates and opinions on best practi… 3 Tweets 10+ useful code snippets to develop iPhone friendly websites When developing websites, you have to care about different browsers, as well as mobile devices [...]

  10. By Website Snippets at Under The Bridge on March 4, 2010 at 2:26 am

    [...] from the awesomely-named Cats Who Code blog is an article of 10+ Useful Code Snippets To Develop IPhone Friendly Websites — some of which are interesting for use in your UIWebView-presented embedded content as well, [...]

  11. By Sitez » links for 2010-03-04 on March 4, 2010 at 9:30 am

    [...] 10+ useful code snippets to develop iPhone friendly websites [...]

  12. [...] 10+ useful code snippets to develop iPhone friendly websites  [...]

  13. By Bokmerke denne veka (weekly) | IKT i læring on March 6, 2010 at 7:34 pm

    [...] 10+ useful code snippets to develop iPhone friendly websites [...]

  14. By Cheatsheet: 2010 03.01 ~ 03.07 - gOODiDEA.NET on March 6, 2010 at 9:45 pm

    [...] 10+ useful code snippets to develop iPhone friendly websites [...]

  15. By Internet Briefing Blog / Wochenendsurf-Tour on March 7, 2010 at 5:19 am

    [...] man seine Website für das iPhone vorbereitet und eine gute Seite auf Deutsch dafür + noch eine. Brilliant-web-design-tutorials und dazu 25 [...]

  16. By links for 2010-03-07 « 個人的な雑記 on March 7, 2010 at 5:01 pm

    [...] 10+ useful code snippets to develop iPhone friendly websites (tags: development iphone) [...]

  17. [...] Border Radius 2. Free mp3 audio book downloads, browse by category 3. 10+ useful code snippets to develop iPhone friendly websites 4. The Future Of CSS Typography – Smashing Magazine 5. Search the PopSci Archives | [...]

  18. By Daily David - davidgagne.net on March 8, 2010 at 10:22 am

    [...] useful code snippets to develop iPhone friendly [...]

  19. By Prepara tu sitio para iPhone | Ayuda WordPress on March 8, 2010 at 7:09 pm

    [...] la recopilación realizada por Cats who code sobre códigos con los que adaptar tu sitio a la visualización en iPhone. Como creo que es de un [...]

  20. By Heti események | I build websites on March 9, 2010 at 3:57 am

    [...] Shared 10+ useful code snippets to develop iPhone friendly websites. [...]

  21. [...]  useful code snippets to develop iPhone friendly websites (0 visite) [...]

  22. [...] 10+ useful code snippets to develop iPhone friendly websites * Detect iPhones and iPods using Javascript * Detect iPhones and iPods using PHP * Set iPhone width as the viewport * Insert an iPhone specific icon * Prevent Safari from adjusting text size on rotate * Detect iPhone orientation * Apply CSS styles to iPhones/iPods only * Automatically re-size images for iPhones * Hide toolbar by default * Make use of special links * Simulate :hover pseudo class aus Delicious/steinhobelgruen  Linkdump       [...]

  23. [...] parlant d’iPhone, Cats who Code donne les 10 principaux bouts de codes PHP, CSS, JavaScript et HTML à connaître pour améliorer au mieux la navigation de son site web [...]

  24. [...] 10+ useful code snippets to develop iPhone friendly websites – [...]

  25. [...] tel: urlsIn a recent post, I showed you how you can use iPhone special link prfixes to automatically call someone. This regular expression will match those tel: [...]

  26. By March 2010 Digest | Brightscape Blog on April 1, 2010 at 12:45 pm

    [...] Who Code: 10 Useful code snippets to develop iPhone-friendly websites Some very practical code snippets for detecting an iPhone, optimising content width, applying CSS [...]

  27. By Web Dev Tutorials 1# | Booto'Blog on April 5, 2010 at 8:49 pm

    [...] 10+ useful code snippets to develop iPhone friendly websites By Jean-Baptiste Jung, March 1st, 2010 Site: Cats Who Code [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting

  • Smashing Network
  • Hosted by VPS.net and Akamai CDN
WordPress Appliance - Powered by TurnKey Linux