Tutorials

Make an iPhone in JavaScript using jQuery

Written by Larry Kubin on January 10th, 2008 | Published in Effects, Tutorials, jQuery

What we’re going to do in this tutorial is make a webapp with an iPhone-like GUI that provides useful features such as flickr photo viewing, YouTube videos, del.icio.us bookmarks, and a slideshow portfolio using nothing but client-side code. We will be leveraging many jQuery plug-ins and effects to make this happen, so we won’t have to actually write many lines of JavaScript code ourselves. The result will be a shiny looking iPhone like the one below, complete with nifty screen transitions. Go ahead and try out the demo first to see what we’re building. If you like it, then continue reading to see how it’s done. You can see it in action on my personal home page or download the source code and play with it on your desktop. jQuery iPhone Downloads

jQuery Basics

In case you haven’t used jQuery yet, let’s run through the basics real quick. To do this tutorial, you’re going to want to know:

1. How to select elements on a page

2. How to manipulate these elements

3. How to handle events (eg. user clicks a button)

4. How to use jQuery effects

5. How to use jQuery plugins

If you already have experience with jQuery, you can skip to the next section which specifically discusses how the “phone” was constructed.

Getting Started

Obviously you’re going to want to get a copy of jQuery, so be sure to download it first. Once that’s done, you just include it in your page with a plain old script tag:

<script type="text/javascript" src="js/jquery.js"></script>

Easy enough. Once that’s done, go ahead an add the following JavaScript code to your page:

<script type="text/javascript">
$(document).ready(function() {
    $("#theButton").click(function() { 
        $(".box").hide("slow");
    });
});
</script>

Then add the following snippet of of HTML to your document:

<button id="theButton">hide the boxes</button>
 
<div class="box">
   Hi, I'm a freakin box!
</div>
 
<div class="box">
  I'm a box too!
</div>

When you are finished, you should have something that looks like the button below - go ahead and click it:



Hi, I’m a freakin box!
I’m a box too!


What Does it All Mean?

You may not realize it, but you just applied many jQuery concepts in the simple example above. The first thing you did was pass a callback function to the document’s ready method. Within this function, you can put all of the JavaScript code that you would like to execute once the document has finished loading. You can think of this as a main() starting point for your program:

$(document).ready(function() {
  // stuff to happen when the doc finished loading
});

Now let’s take a look at the code that was in our callback function:

$("#theButton").click(function() { 
    $(".box").hide("slow");
});

First notice the syntax for selecting an element. It is similar to how you apply a style using CSS. To select an item by ID, you don’t use document.getElementById(’some_id’). Just use $(”#some_id”). Similarly, you can select all elements with a specific class name with $(”.some_class_name”). So in the code snippet above, we passed a callback function to the button that will be executed when the button is clicked. When the button is clicked, all elements with the class name of “box” will be hidden using a jQuery effect function called hide(), which accepts the parameter “slow” to specify that the element should slowly ease out rather than disappear immediately.

Creating the Phone

Now that we are comfortable with some of the jQuery concepts, let’s start building our phone. Here are the steps:

  1. Create the general layout of the phone using simple HTML and CSS
  2. Create buttons for the phone using Photoshop or your favorite image editor
  3. Attach event handlers to each of the buttons to show the appropriate screen when a button is clicked
  4. Spice things up and pull in some external content by throwing in a few jQuery effects and plugins.

Layout

The basic idea here is that we want to create a layout that is shaped like an iPhone. This is easy, since an iPhone is shaped like a rectangle. Just create a div that is about 320 pixels wide for the phone “container”, then stack div elements within the phone to contain the buttons, the screen, and the top of the phone:

<!-- this is the fixed width container for the phone components  -->
<div id="phone">
  <!-- the place where you put your ear -->
  <div id="ear"></div>
 
  <!-- the screen, where all of the content is displayed -->
  <div id="screen"></div>
 
  <!-- the four main buttons go here -->
  <div id="buttons"></div>
 
  <!-- this holds the main button that takes you back to the home screen -->
  <div id="home_button"></div>
</div>

Buttons

The buttons are easier to create than you think. Just follow the following steps:

  1. Create the button shape by drawing a square using the rounded rectangle tool.
  2. Apply a gradient overlay
  3. Cut out an ellipse on the top half of the button to give the button it’s glare.
  4. Add an icon layer on top of the button
  5. Apply a drop shadow to the button

This process is fully described in this excellent tutorial. Once you are done creating your buttons, just place them in the buttons div.

Screens

The next task is creating the screens. All we do here is create divs of class “screen”, with each screen occupying a 320 x 320 pixel square. For this tutorial, I created the screens all at once, and started them all out as hidden. Only screens that are of class “current” are visible. When a button is pressed, we hide the current screen, show the screen associated with that button, then set the new screen as the current screen.

Hooking it up

We could select a specific button (eg. contact), then tell it to hide the current screen and show a specific screen (eg. the contact screen) when it is clicked. For instance, the following code shows the contact div when the contact button is clicked and the delicious screen when the delicious button is clicked:

$("#contact").click(function(){
    $(".current").hide();
    $("#contact_screen").addClass("current").appendTo("#screen").show("slow");
});
 
$("#delicious").click(function(){
    $(".current").hide();
    $("#delicious_screen").addClass("current").appendTo("#screen").show("slow");
});

As you can see, this is going to suck. As we add more buttons and more screens, we have to create a callback function for each one. A better approach would be to have a general function that accepts an element’s ID, hides the current screen, and displays the screen with the ID that was passed in:

// hides the current screen, sets a new screen as current, then shows the new screen
function setCurrent(id) {
    // hide whatever is on the screen
    $(".current").hide();
 
    // show the screen for the button that was pressed
    $("#" + id + "_screen").addClass("current").appendTo("#screen").show("slow");
}

Notice how our selector is built dynamically with “#” + id + “_screen”. So when “contact” is pressed, we show “contact_screen”. All we need now is to automatically associate a click handler with all elements of class “button”, like so:

$(".button").click(function(){
    setCurrent(this.id);
});

Plugins

We can make our phone do interesting things without much effort by using the jQuery Cycle, Clock, and Flickr plugins. Furthermore, we can give our phone rounded corners by using the rounded corner plugin.

Using a jQuery plugin is as simple as downloading the plugin’s .js file, including it in your page, then instantiating it and customizing it with your parameters. Here is all of the code required to give the phone div rounded corners, add a working clock, pull in my del.icio.us bookmarks, and show my flickr photos.

$("#phone").corner("30px");
 
$(function($) {
    $('.jclock').jclock();
});
 
$('#delicious_screen').delicious('larry.kubin', {favicon: false, append: true});
 
$('#photos_screen').flickr({
    api_key: 'c1c009c8a405ad1fe48d7a0412320e64',
    type:    'photoset',
    photoset_id: '72157603625130568',
    thumb_size: 'm'
});

Yes folks, it’s that easy. With the plethora of jQuery plugins out there, you can put together some fancy, responsive demos for fun or profit without writing much code at all. In this tutorial, I only used basic jQuery effects and a few plugins. If you were to spend enough time with it, you could probably pull off all sorts of neat tricks, like flipping photos over to show their metadata, cover flow, or rotating the phone div to a landscape view!