Mobile web application framework match-up, Part 3: Boost your next mobile web app with jQTouch

The interest in mobile development, which includes mobile web applications, has never been higher. Some of the developers interested in mobile web approach it from either a desktop or a server-side background. However, many are looking to apply their current web development skills to the mobile web, so they don't want to learn something completely different just to start developing for mobile users. This is part of the reason they are looking to the mobile web instead of native mobile development. In the world of web development, there are many client-side frameworks, but jQuery is arguably the most popular among them. So it stands to reason that there are many web developers interested in mobile who already know jQuery quite well. These developers will be pleased to learn about jQTouch—a web framework based on jQuery and designed for mobile web development. This article will take a look at jQTouch from the perspective of mobile web developers.

Michael Galpin, Software Architect, eBay

Michael Galpin's photoMichael Galpin is an architect at eBay and a frequent contributor to developerWorks. He has spoken at various technical conferences, including JavaOne, EclipseCon, and AjaxWorld. To get a preview of what his next project, follow @michaelg on Twitter.



07 December 2010

Also available in Chinese Japanese

About this series

Mobile development has taken off, so many developers are choosing to go the mobile web route instead of writing the same application repeatedly for each different mobile platform. However, one of the things that you give up by "going web" is the application frameworks that make life easier for developers of native mobile applications. As a result, several web application frameworks are emerging. In this four-part series, we will look at four of these frameworks: SproutCore, Cappuccino, jQTouch, and Sencha Touch. We will compare the features of these frameworks and evaluate the pros and cons of using them to build a mobile web application.


Prerequisites

This article presents an overview of jQTouch. As mentioned earlier, this framework is based on jQuery. If you already know jQuery, then jQTouch will be very familiar to you. Though familiarity of jQTouch is not required for this article, a knowledge of JavaScript, HTML, and CSS is. All of the code here is purely client-side and can be deployed to any web server. For the article, jQTouch 1.0-beta2 was used with jQuery 1.3.2. See Resources for links to these tools.


Introduction to jQTouch

So far, this series has considered two web application frameworks that borrow heavily from Apple's Cocoa application framework. These frameworks abstract away HTML and CSS, the key presentation technologies of the web. The Cappuccino framework even abstracts away a lot of JavaScript, replacing it with its own programming language, Objective-J. The jQTouch framework takes a much different approach. It embraces core web technologies, making common, boilerplate tasks easier and more intuitive.

Most of what makes jQTouch appealing is that it builds on top of jQuery. It is technically a jQuery plug-in that adds mobile-specific functions and styling to applications. In particular, it adds styles and visual effects designed to take advantage of the capabilities of the iPhone. Though many of its features work well on other mobile devices, jQTouch is definitely designed with the iPhone in mind. Take a look at a simple mobile web application built on top of jQTouch.


jQTouch application development: Leveraging web skills

As mentioned earlier, the jQTouch framework takes a very different approach to web application development than other frameworks, like SproutCore and Cappuccino. It has some common points with those frameworks as well; similarly, it allows you to simply retrieve data from your servers and create the entire user interface on the client side. However, unlike those frameworks, it does not require you to use this approach. Indeed, it builds on HTML and CSS, not just JavaScript. To see this, begin with the basics.

jQTouch basics

The application that you will build with jQTouch will be very familiar if you have read the previous two articles in this series. It is an employee directory for an intranet web application. You will load the same data that you have used in the previous installments of this series. However, jQTouch offers more mobile-friendly user interface elements, so it will have a better UI in turn. You will show the data in both a table format and a list format. Start with a home screen, shown in Listing 1, which allows the user to choose between the list and table format for the data.

Listing 1. Application essentials and home screen code
<!doctype html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Intranet Employee Directory</title>
    <style type="text/css" media="screen">
        @import "jqtouch/jqtouch.min.css";
    </style>
    <style type="text/css" media="screen">
        @import "themes/jqt/theme.min.css";
    </style>
    <script src="jqtouch/jquery.1.3.2.min.js" type="text/javascript" 
        charset="utf-8"></script>
    <script src="jqtouch/jqtouch.min.js" type="text/javascript" 
        charset="utf-8"></script>
    <script type="text/javascript">
        var jQT = $.jQTouch({
          icon : 'icon.png'
      });
    </script>
</head>
<body>
    <div class="home">
        <div class="toolbar">
            <h1>Employees</h1>
        </div>
        <ul class="edgetoedge">
            <li class="arrow"><a href="#list-style">List</a>
</li>
            <li class="arrow"><a href="#table-style">Table</a>
</li>
        </ul>
    </div>
</body>
</html>

The code in Listing 1 contains the essentials of a jQTouch application. Two CSS files and two JavaScript files have been included. To use jQTouch, you need both of the JavaScript files. These contain the jQuery library and the jQTouch plug-in library. You also must have the first of the CSS files (jqtouch.min.css). The other CSS file is an optional theme. jQTouch includes two themes, one to match the iPhone (Cocoa Touch) UI, and another (jqt) that is more neutral. In Listing 1, the jqt theme CSS file has been included. Finally, you initialize the jQTouch object. Many options can be passed to this constructor. Here, you have only specified an application icon, which will be the one used if the user 'installs' the application, like in Figure 1.

Figure 1. Mobile web application installed to iPhone home screen
Mobile web application installed to iPhone home screen

Going back to Listing 1, the rest of the code is basic HTML. You have a div with class home. There is nothing special about this class. However, if you are familiar with jQuery, then you will recognize this as a page in jQuery. Each page (screen) in your web application will be a div on a single HTML page. So in this case, your page has a div at the top with class toolbar. This special class is one of several defined styles in the core jQTouch CSS file. Next, you have an unordered list with class edgetoedge—another jQTouch style. Each entry in the list is a link to another section on the HTML page. Again, this is another common jQuery paradigm for linking between the pages of a web application. Figure 2 shows how the application created in Listing 1 looks on an iPhone.

Figure 2. Home screen on an iPhone
Home screen on an iPhone

Figure 2 shows a relatively simple user interface; all the code needed to create it is in Listing 1. All you have used at this point is some HTML. The elements in your list are also clickable, and will lead to other pages of your application. However, those pages will need some Ajax-loaded data to function properly. As you will see, Ajax is another place where jQuery excels.

Dynamic data with jQuery

So far, you have leveraged jQTouch's mobile-optimized styles to take simple HTML and turn it into an attractive mobile user interface. Now generate both a dynamic list and a dynamic table. First, retrieve the data for these interfaces as shown in Listing 2.

Listing 2. Retrieving data with Ajax
$(document).ready(function(){
    $.getJSON('employees.json', function(data){
        data.forEach(addEmployee);
    });
 ...
});
function addEmployee(e){
    addEmployeeToList(e);
    addEmployeeToTable(e);
}

In Listing 2, you are only using basic jQuery functionality. Load the data using Ajax from the server as soon as the initial page loads. This is a common paradigm in web development that jQuery makes easy by using the $(document).ready function. This function takes a function as its input parameter. In this case, you used an anonymous inline function, also known as a closure. This closure will be executed as soon as the initial page finishes loading. jQuery provides numerous convenience functions for working with Ajax requests and responses. In this case, the data will be formatted as JSON, so use jQuery's getJSON function. This takes a string representing the URL endpoint of the request. The function will use an XMLHttpRequest object behind the scenes to make an HTTP GET request to this URL.

The function also takes another function as a callback for when the Ajax request returns successfully from the server. (It can also take another optional callback function to handle errors, but we have left that out to keep this example simple.) Once again, you have passed a closure as the callback function; this function expects to receive an array of employee objects—the same data that you have worked with in the previous articles in this series. The callback function then uses the forEach method on the Array object. You might not be familiar with this function, since it is not available on older browsers. However, it is available on the more modern browsers that you are targeting here. It takes a function as its parameter and applies the function sequentially to each object in the Array. Though you can pass another closure to it, instead pass it a reference to another function called addEmployee. This function delegates to separate functions for adding the employee object to the list and to the table. Take a look at how these functions dynamically create UI using jQTouch.

Dynamic UI elements with jQTouch

If you go back to Listing 1, you will notice that your home screen had links to two other pages, one for the list view of the data and another for the table view of the data. We mentioned earlier that this leverages jQuery's convention of using divs on the page to stand for separate pages of your application. The HTML for those pages is shown in Listing 3.

Listing 3. List and table HTML
<div id="list-style">
    <div class="toolbar">
        <h1>List</h1>
        <a class="button back" href="#">Back</a>
    </div>
    <ul class="edgetoedge" id="eList"></ul>
</div>
<div id="table-style">
    <div class="toolbar">
        <h1>Table</h1>
        <a class="button back" href="#">Back</a>
        <a class="button flip" href="#new">+</a>
    </div>        
    <table>
        <thead>
            <tr>
                <td>Name</td>
                <td>Phone</td>
                <td>Email</td>
            </tr>
        </thead>
        <tbody id="eTable"></tbody>
    </table>
</div>

The above code is, once again, just simple HTML. Examine one page at a time. For the list page, you once again have a nested div that uses the toolbar style. It has a simple heading, along with anchor text. Notice the anchor has the class button back. Again, this is a style provided by jQTouch. It will create a back button for the page that will look native to mobile platforms. Figure 3 shows how this toolbar section will look on an iPhone.

Figure 3. List page toolbar
List page toolbar

As you can see, jQTouch allows you to easily create high quality interfaces with very little code. Returning to Listing 3, you can see that you also have an empty, unordered list. Notice that it uses the edgetoedge style provided by jQTouch that is well suited for items you want to span the full screen horizontally. Fill this list with the data that you retrieved from the server in Listing 2, as shown in Listing 4.

Listing 4. Creating a list
function addEmployeeToList(e){
    var list = $("#eList");
    var text = e.firstName + " " + e.lastName +
         ", " + e.phone + ", " + e.email;
    var li = $("<li>").html(text);
    list.append(li);
}

Dynamically creating HTML elements is one of the more tedious tasks in typical web development; once again, this is where jQuery shines. The code in Listing 4 is pure jQuery. You first get a reference to the unordered list from Listing 3 by passing a CSS selector to jQuery. Create the text that you want to put in the list, and then use jQuery's convenience methods to create the DOM element and append a text node to it. Finally, add this to the unordered list. Figure 4 shows how the list will look using mock data.

Figure 4. List view
List view

To create your list, use some basic jQuery code to retrieve data from the server and to create some standard HTML elements (along with an HTML skeleton that referenced jQTouch styles). That is all that is necessary to create the UI shown above. If you test it on a mobile device, you'll notice that it loads quickly and scrolls smoothly. Now look at how you can create a table to display this same data.

Going back to Listing 3, notice that your table page is similar to the list page. It has a similar toolbar, only with one additional button. (You'll take a look at what that button does shortly.) It also has a skeleton table—that is, a table with a header but no data. The data will be the same as shown in the list. You just need to create rows for your table, as shown in Listing 5.

Listing 5. Creating table rows
function addEmployeeToTable(e){
    var table = $("#eTable");
    var tr = $("<tr>")
            .append($("<td>").html(e.firstName + " " + e.lastName))
            .append($("<td>").html(e.phone))
            .append($("<td>").html(e.email));
    table.append(tr);
}

The code in Listing 5 is similar to the code in Listing 4. You can rely on jQuery's convenience methods to create HTML DOM elements and append them together. Notice the convenience of the append function that allows you to use a builder pattern to quickly create a table row with three cells in it. Figure 5 shows how this will look with mock data.

Figure 5. Table view
Table view

The anticipated user interface is shown in Figure 5. You can certainly make the table a little fancier by using standard CSS. You will probably notice the plus symbol (+) button in the top right of the toolbar. Looking back at Listing 3, notice that this links to another page called New. Also notice that the class on this link is button flip. This will once again create a native-looking button that serves as a link to the new page. The flip part of the class indicates to jQTouch that a flip transition should be used. This is a proprietary WebKit CSS 3D animation that is currently only supported on the iPhone, and one of many 2 and 3D animations that jQTouch makes it easy to tap into. When you tap the plus button, a page for creating a new employee form is displayed. Listing 6 shows the code for this page.

Listing 6. New employee dialog
<div id="new">
    <div class="toolbar">
        <h1>Add Employee</h1>
        <a class="button cancel" href="#">Cancel</a>
    </div>
    <form id="addEmp" method="post">
        <ul>
            <li><input type="text" placeholder="First Name" id="fn" 
                name="firstName" />
            </li>
            <li><input type="text" placeholder="Last Name" id="ln" 
                name="lastName" />
            </li>
            <li><input type="email" placeholder="Email" 
                autocapitalize="off" id="email" name="email" />
            </li>
            <li><input type="tel" placeholder="Phone" id="phone" 
                name="phone" />
            </li>                                
        </ul>
        <input type="submit" class="submit" value="Submit"/>
    </form>
</div>

The code in Listing 6 is straightforward HTML. The toolbar was created by using a div with the toolbar class applied to it. This time, you have a Cancel link, which is styled using the button cancel classes. Of course, the button class makes it into a button. The cancel class will cause the link to return to the previous page, similar to the back class. However, unlike the back class, it will automatically use the reverse of the effect that was used to transition to this page.

After the toolbar, you have a simple HTML form wrapped inside an unordered list. You might notice several unusual things. First, all of the fields use the placeholder attribute. This is an HTML5 feature that causes the placeholder text to be shown until that field gains focus. This is a convenient alternative to using a label, especially since a mobile screen is so much smaller. Notice that the email input has an autocapitalize attribute set to false. This is another iPhone-specific feature that tells the browser to temporarily disable the OS level autocapitalization for text typed into this field. Also notice that both the email and phone inputs have unusual types (email and tel). This is a feature supported on both iPhone and Android browsers that tells the browser to bring up different keyboards when focus is on these input fields. Figure 6 shows how each of these fields looks.

Figure 6. Android and iPhone browsers focused on tel and email inputs
Android and iPhone browsers focused on tel and email inputs

The last thing to notice about the form in Listing 6 is the Submit button. Notice that its class is submit. This is another jQTouch class that makes the button more attractive, at least on an iPhone. Listing 7 shows how to set up an event handler with jQTouch for when a form is submitted.

Listing 7. Handling form submission
$(document).ready(function(){
    // Ajax call can be found in Listing 2
    $("#addEmp").submit(function(){
        var e = {
            firstName : $("#fn")[0].value,
            lastName : $("#ln")[0].value,
            email : $("#email")[0].value,
            phone : $("#phone")[0].value
        };
        addEmployee(e);
        jQT.goBack();
        return false;
    });
});

Notice that this is part of the initialization code that you saw in Listing 2. Here, you have used another jQuery selector to get a reference to the form shown in Listing 6. jQuery provides an easy way to hijack the form's submit event. Once again, pass in a closure to handle this event. In the closure, create a JavaScript employee object, but retrieve values from the form. Then use the addEmployee function that you saw in Listing 2 to add the new employee to both the list and record views. Next, use a jQTouch function, goBack. This works similarly to the cancel button that you saw earlier, transitioning back to the previous page. Finally, return false to prevent the form from being submitted. Obviously, this code only adds the new employee to the local screens. You can imagine a server-side API that can be used to add the employee to a shared database, and you can use jQuery's excellent Ajax and form functions to serialize the data and send it back to the server. This completes the functionality in the sample application. Now that you have built a mobile web application using jQTouch, take a look at how it stacks up.


Mobile web applications with jQTouch

Though the jQTouch framework might be a simple plug-in on top of jQuery, it certainly extends the philosophy of the jQuery framework by embracing core web technologies and making development easier. It adds a lot of mobile-optimized user interface elements that allow you to easily apply simple CSS styles to HTML and get sophisticated results. Further, the themes and features like page transitions bring a native feel to the applications.

When it comes to handling application logic, jQTouch does not attempt to abstract away the workflow of things as other frameworks do. Instead, it relies on jQuery for powerful tools that make tasks like form handling, Ajax, and page transitions much easier. If you are already an experienced web developer who is comfortable with how web applications work—and with the web's power team of HTML, JavaScript, and CSS—then jQTouch is probably a great fit for you. You can start producing attractive, easy-to-use mobile web applications very quickly. However, if you want to take a more structured approach, then you'll have to add that structure yourself. This can make a huge difference for large, complex applications that will be worked on by a team of developers. Further, jQTouch doesn't try to change the typical workflow involved in creating web applications—it just tries to make each step in the workflow easier. Other frameworks go further by abstracting many of the steps and providing a more logical flow with less boilerplate.

Finally, one other jQuery project deserves to be mentioned. That project is the aptly named jQuery Mobile project (see Resources). Unlike jQTouch, it is not a plug-in; it shares many common features with jQTouch, but it has larger goals. It aims to provide more UI widgets and make them work across platforms. For example, the application you built works OK on an Android phone, but it is obviously intended for the iPhone. jQuery Mobile applications are designed to work equally well on both Androids and iPhones, as well as on several other platforms. It is not a plug-in for jQuery; instead, it is built from the ground up for mobile, which translates to leaner, meaner code: 69 KB of JavaScript and 8KB of CSS for jQTouch compared to12KB of JavaScript and 6KB of CSS for jQuery Mobile. The very first alpha version of this project was released while this article was being written, and it is definitely rough around the edges. However, if jQTouch appeals to you, stay up to date on jQuery Mobile as well.


Conclusion

This article has demonstrated that you can apply your web development skills to mobile phones with a little help from jQTouch. For many developers, this might be the most immediate way to go mobile. If you are a web developer, it's likely that you already know jQuery, which make jQTouch even more appealing. Dig deeper into the excellent jQTouch documentation and explore many more of its features. It makes many of the advanced HTML5 features available to you on the iPhone and Android browsers more readily available for use in your mobile web applications. In the last article in this four-part series, explore another project that also takes the embrace-the-web approach to mobile, Sencha.


Download

DescriptionNameSize
Article source codeintradir-jqtouch.zip104KB

Resources

Learn

Get products and technologies

  • Download jQTouch. For this article, jQTouch 1.0-beta2 was used.
  • Visit the main jQuery site and download the source code. For this article, jQuery 1.3.2 was used.
  • Get the Apache HTTP Server.
  • Download IBM product evaluation versions, and get your hands on application development tools and middleware products from DB2, Lotus, Rational, Tivoli, and WebSphere.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=594592
ArticleTitle=Mobile web application framework match-up, Part 3: Boost your next mobile web app with jQTouch
publish-date=12072010