" a brain is like a parachute ... it is only useful when it is open "

Delving into jQuery Mobile: Part 1

A few days ago I started working on a mobile web site for a friend. The site was a simple one as it was purely a click through site that we were going to use as a discussion point ,so I didn't want to spend too much time on it as I knew that most of it would be re written a week or so later. When it comes to mobile sites I am an n00b. I have made mobile applications but never a mobile web site. I did some googling around and some tweeting and found out what libraries people were using for their sites and settled on the jQuery Mobile framework (http://jquerymobile.com/) .

I could give you a list of reasons why I didn't choose some of the other frameworks but in all honesty it pretty much came down to the fact that it is a jQuery framework. jQuery is one of those libraries that I use in all my web sites. It is one of the first things I add to the project and it is going to be something that I will probably use for years to come. So when I saw that they had a mobile framework, even though it is currently in an alpha release, I knew that was what I was going to use and in all honesty, it has lived up to my expectations of anything from the jQuery team. The framework is probably one of the easiest frameworks around. All in all, including the time it took me to learn jQuery Mobile, I was able to create the click through site in under 4 hours. It is that simple!

So what exactly is jQuery Mobile? Well it is a lightweight framework that is based on jQuery and jQuery UI that allows you to create an application that performs across multiple devices. For a list of compatible devices go here (http://jquerymobile.com/gbs/). The framework comes jam packed with touch-optimized layouts, UI widgets, themes as well as mobile specific events. It is ultra simple to code in and doesn't even require any extra JavaScript. In the examples below you will see that I don't actually write any JavaScript at all. I don't even need to instantiate jQuery, I just need to write some HTML using some of the HTML5 markup.

Creating your first page

A jQuery mobile page consists of 2 main components, a page and content. The page is the container for everything you see on the screen, and the content is what the user sees. In addition to this, you can also specify a header and footer. These are technically optional but I would not recommend creating a site without at least the header. The jQuery Mobile framework loads its pages using AJAX calls and also handles the history management. The back button for your application is displayed in the header so if you do not create a header on your page there will be no place for the back button. The footer, as well as the header, is capable of holding buttons, but is not a necessity for your application so if you don't need it then you don't need to use it. I will discuss the header and footer more in depth later in the series, but first lets look at our simple page.

Here is the code for an example page:

view plain print about
1<!DOCTYPE html>
2    <html>
3        <head>
4        <title>Sample Page</title>
5        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.css" />
6        <script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
7        <script src="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.js"></script>
8    </head>
9    <body>
11        <div data-role="page">
12            <div data-role="header">
13                <h1>Sample Page</h1>
14            </div>
16            <div data-role="content">    
17                Sample Content
18            </div>
20            <div data-role="footer" class="ui-bar">
21                &nbsp;
22            </div>
23        </div>
24 </body>
25 </html>

The code above creates a single page that has a header, footer and content.

Here is how it looks:

Here are a few things to note in the code. Notice that the first line specifies the HTML5 'doctype'. This is necessary to be able to take full advantages of many features. Also notice the order in which the JavaScript files are included. If you were to extend this page and add your own JavaScript you should make sure that you include that JavaScript BEFORE the jQuery mobile library is included. As soon as the library is included it will initialize so you will want to have all your scripts loaded prior to that. You will also see the use of the data-role attribute. This attribute is used throughout the jQuery Mobile framework. It is used to tell the framework what role that dom element has in the page. In this example we use the page, header, content and footer roles. In addition to these there are roles specific to navigation, UI, lists and so on. They are heavily used and will be the main attribute you will want to learn about.

Now having a single page is nice and all, but lets look at switching between pages. There are actually 2 ways in which pages can be loaded. The first we will look at is where we have multiple pages in a single file.

view plain print about
1<!DOCTYPE html>
2    <html>
3        <head>
4        <title>Sample Page</title>
5        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.css" />
6        <script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
7        <script src="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.js"></script>
8    </head>
9    <body>
11        <div data-role="page" id="page1">
12            <div data-role="header">
13                <h1>Sample Page 1</h1>
14            </div>
16            <div data-role="content">    
17                <p>
18                    Sample Page 1
19                </p>
20                <p>
21                    <a href="#page2">Go to page 2</a>
22                </p>
23            </div>
25            <div data-role="footer" class="ui-bar">
26                &nbsp;
27            </div>
28        </div>
30        <div data-role="page" id="page2">
31            <div data-role="header">
32                <h1>Sample Page 2</h1>
33            </div>
35            <div data-role="content">    
36                <p>
37                    Sample Page 2
38                </p>
39                <p>
40                    <a href="#page1">Go to page 1</a>
41                </p>
42            </div>
44            <div data-role="footer" class="ui-bar">
45                &nbsp;
46            </div>
47        </div>

The code above will create 2 pages, 1 that says sample page 1 and one that says sample page 2. Clicking on the links on the page will take you between the two pages.

Here is how it looks:

If you were to compare the code to the previous example you would notice that this was achieved by adding a second div with a page role. In a single file you can have multiple items with the page role. Also notice that I did not add any code to hide the second page on load. The framework detects that there are multiple pages and only displays the first. To switch between the pages we use a simple href tag and use anchor notation for the specific div we wish to display. It is important when building a page like this that all pages have id's and that they are all unique.

Navigating between Pages

Now being able to navigate between content in a page is nice, but in most situations we will want to be able to call different pages. If all our content were to be in one file then the initial page load could take an age, especially when you remember that your users are accessing this via a cell phone. So lets look at the second way to load a page.

To navigate to an external page all you need to do is to use an href tag and call the page you want, just like you would when creating a regular web page. The difference with jQuery Mobile is actually with how the page is loaded. Instead of reloading the page, jQuery Mobile parses out the href tag and makes an AJAX call to the page (Hijax) and loads it that way. The user will then be displayed the usual spinning waiting box and then the page will be loaded. If, for some reason, the page does not exist or there is an issue, the user will be given an error message and the user will be kept on the current page.

Using this Hijax method can be a bit confusing when debugging your application. I initially ran into this problem when I was using the jQuery Mobile docs and example site. Unlike their other web sites, there is little example code displayed to you, more focus is paid to the outcome. So to get a better understanding you normally have to look at the source code. Now if you were to right hand click on the page and go to view source you would get some code that you would not be expecting. You would, in fact, be viewing the source code of the home page. As all the pages are loaded in via AJAX calls the source code of the page does not actually update. If you inspect the url you will see that the url shows the initial page you loaded followed by a # sign and then the page you are currently viewing, like bellow:


Now if you want to actually see the source code the simple way around this is to remove the # sign and load the page. The page will now be reloaded and if you view source you will see the source code of the page being displayed.

Listing out your data

When listing out data in a mobile based web site it is common for you to try and mimic the look and feel of native mobile applications. With the jQuery Mobile framework that hassle is handled for you. Within the framework is an extensive UI library that will style your lists for you. In addition, the framework also has additional support for events such as swipes and drags.

Here is a simple example that uses lists:

view plain print about
1<!DOCTYPE html>
2    <html>
3        <head>
4        <title>ColdFusion Art Gallery</title>
5        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.css" />
6        <script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
7        <script src="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.js"></script>
8    </head>
9    <body>
11        <cfquery name="qArt" datasource="cfartgallery">
12            SELECT
13                artists.artistID,
14                firstName,
15                lastName,
16                artID,
17                largeimage,
18                artname
19            FROM
20                ARTISTS
21            INNER JOIN
22                ART ON artists.artistID = art.artistID
23             ORDER BY
24                lastname,
25                firstname,
26                artists.artistid
27        </cfquery>
29        <div data-role="page">
30            <div data-role="header">
31                <h1>CF Art Gallery</h1>
32            </div>
34            <div data-role="content">    
35                <ul data-role="listview">
36                    <cfoutput query="qArt">
37                        <li>
38                            <h3 ><a href="art.cfm?artID=#qArt.artID#">#qArt.artName#</a></h3>
39                        </li>
40                    </cfoutput>
41                </ul>
43            </div>
45            <div data-role="footer" class="ui-bar">
46                &nbsp;
47            </div>
48        </div>

Here is how it looks:

In this example we query the cfartgallery database that comes packaged with ColdFusion and list out the art records. Inside the content div we have a simple UL, LI structure and we have specified that the data-role of the UL is ListView. That's it! Simply using the listview data role has allowed us to create a list that looks and functions like a native application.

Testing your application

When it comes to testing your applications it is not necessary for you to always test it with your mobile device. Not only will that slow down your development process but it is only going to test it for your phones settings. What I would recommend is downloading Opera Mobile. Emulator (http://labs.opera.com/news/2010/04/22/) The emulator is designed to help you test mobile web sites and lets you specific the size of the display as well as the orientation. Additionally, if you want to just make sure a piece of functionality works and you are not necessarily testing the layout then you can just load the page in your favorite browser.

So hopefully this post has shed some light on the jQuery Mobile framework. We have only covered some of the very basic aspects of the framework but it will hopefully have wet your appetite. Check back soon for the next post which will cover detail pages, buttons, popups and more!

Related Blog Entries

Thanks Simon. I was able to to put together a very quick demo for my execs. They've been thinking of outsourcing mobile.
# Posted By Yaron Kohn | 12/7/10 12:34 PM
@yaron Glad to hear it helped. It is surprising how easy it is to build pages using jQuery Mobile. Make sure to check my next post which is going to cover all the cool ways to list data
# Posted By Simon Free | 12/7/10 1:04 PM
Great article! I was getting frustrated by my inability to look at the source on the Docs and Demo page but your simple suggestion to remove the "#" did the trick and is much appreciated.
# Posted By Andrew Barrett | 12/12/10 8:24 PM
How do you handle external links so they don't pen in a new window but rather they load into the jquery moblie page with navigation.

I am trying to build a RSS reader and the links all are navigating to a new page instead of being loaded into the existing page.

Thanks -
# Posted By Chris Bizzell | 12/16/10 10:01 AM
Many thanks for this excellent share. I absolutely enjoyed checking it and will definitely share it with my friend. =-=
# Posted By Jarod | 9/13/11 7:59 AM
Thanks for the tip on opera emulator that's very helpful!
# Posted By Preston | 10/21/11 5:10 PM

BlogCFC was created by Raymond Camden