Build iPhone, Android and iPad Applications using jQTouch

Exclusive offer: get 50% off this eBook here
jQuery 1.4 Reference Guide

jQuery 1.4 Reference Guide — Save 50%

This book and eBook is a comprehensive exploration of the popular JavaScript library

$23.99    $12.00
by Mambe Nanje Churchill | June 2010 | Open Source Web Development

With jQTouch, web developers can build smartphone interfaces for their existing web applications by simply transforming an existing Document Object Model (DOM) structure into an interface that works, looks and feels like native iPhone or Android application. In this tutorial by Mambe Churchill Nanje, we will learn how to develop such an application.

 

jQuery Plugin Development Beginner's Guide

jQuery Plugin Development Beginner's Guide

Build powerful, interactive plugins to implement jQuery in the best way possible

  • Utilize jQuery's plugin framework to create a wide range of useful jQuery plugins from scratch
  • Understand development patterns and best practices and move up the ladder to master plugin development
  • Discover the ins and outs of some of the most popular jQuery plugins in action
  • A Beginner's Guide packed with examples and step-by-step instructions to quickly get your hands dirty in developing high quality jQuery plugins
        Read more about this book      

(For more resources, see here.)

jQuery is a javascript framework that simplifies javascript development life cycle for web applications. Its greatest force comes from the ease of use and the huge number of plugins available. As a result of which javascript developers are exposed to a large number of enterprise components like Sort Tables, Editable Tables with Ajax and also web application components for animation, data manipulation.

One such plugin with very powerful effects is the jQTouch; this plugin can be used by any web application developer with small experience in jquery to build applications for iPhone, iPad and Android devices. For now, just to get a feel, you can point your internet enabled iPad, iPhone or Android device to http://www.afrovisiongroup.com/twigle and test the application. Other examples of applications that can be developed using jQtouch include Gmail for the iPad or facebook touch.

Getting Started

Before we start using jQTouch, I would love to put across a few facts about jQTouch.

jQTouch is a plugin for jQuery which means it only enhances jQuery to build smartphone applications that support swiping, and all the other touch gestures. Before you begin development with jQTouch, I would suggest you get comfortable with jQuery.

jQTouch applications are not developed like regular web applications, where in an index page will be loaded with links that lead to other pages, and each page is loaded from the server every time a visitor clicks on a link. With jQTouch, all the pages are loaded once inside the index.html and each page is represented as a seperate div element in the index page. For example, the following html code snippet (<div id='page_name'>content</div>) represents a page in your jQTouch application and a link to that page is as follows (<a href='#page_name'>link to page name</a>). You can have as many pages as you want with all the pages having links to other pages inside the index.html file, but remember all this is stored in one single file index.html. The link clicks and navigation actions are implemented using javascript inbuilt into jQTouch. You will get to understand this as we implement twigle. Let's first get to know more about twigle. It is a twitter search application for smartphones loaded from the web. We will use jQTouch for client side development, jQuery ajax plugin for the server side communication and PHP in the backend to get the search results from the twitter Search API.

jQTouch comes with javascript files and css files with themes. This defines the look and feel of the application. You won't have to bother about the design as the plugin already comes with predefined styles and graphics from which you can use as the base and extend it further to create your own unique looks. There are two themes that come with the plugin: apple theme and jqt theme.  Just like the name implies, the apple theme looks and feels like native iPhone OS apps.

The plugin styles are predefined for the toolbar, rounded button, etc. You will discover this as we move on.

jQTouch applications are basically developed in a single file, usually index.html. It contains the html code, javascript code and the styling. Everything in your application happens inside this file which gets loaded into your smartphone once like gmail and the other google applications.

For example

[code] 
 <html>
<head>
</head>
<body>
<div id='home'>
<div class='toolbar'>
 Home Page
</div>
<div>
 this is the home page
</div>
</div>
</body>
</html>
[/code]

The above html code should produce the following:

After installing and initializing the jQtouch plugin with the apple theme, you should have the following:

Notice how the <div class='toolbar'><h1>Home Page</h1></div> gets styled into the iPhone or iPad toolbar's look and feel. Now, on the whole, the page looks more or less like a native iPhone application.

Developing with jQTouch

To develop your iPhone OS or Android OS applications with jQtouch you need to have jQuery and jQTouch libraries which you can download from http://www.jqtouch.com/.

Next, get your favorite code editor (dreamweaver, notepad ++, etc) and we can get started.

Remember, we are going to look at how to develop an application like twigle here. You can check out the demo of the application at http://www.afrovisiongroup.com/twigle. This is a twitter search application for smartphones loaded from the web. We will use jQTouch for client side development, jQuery ajax plugin for the server side communication and PHP in the backend to get the search results from the twitter Search API.

Lets Get to work:

Create a folder on your local web server directory called twigle

Download the jQTouch package and unzip it into the folder twigle, this will give you the following structure:

twigle/demos(this folder contains the sample applications. You can look at the source to learn more about these)

/extensions(this folder contains jQTouch extensions that are like its own plugins)

/jqtouch(this folder contains the javascript and css files needed for jQTouch to work)

/themes (this folder contains the theme files and you can create your own themes too)

/license.txt

/readme.txt

/sample.htaccess

Now we create two files in the twigle folder: index.html and twigle.php

The index.html will hold our application views(pages represented as html DIV Tags) and the twigle.php will be our business logic backend that connects the twitter API to our index.html front end. Javascript and AJAX communications comes between the index.html and the twigle.php to load twitter search results for any given search request.

Paste the following code into the index.html file:

[code] 
<!doctype html> 
<html> 
    <head> 
        <meta charset="UTF-8" /> 
       
</head>
<body>
<div id="home"> 
        <div class="toolbar"> 
           <h1>TWIGLE</h1> 
           <a href="#info" class="button leftButton flip">Info</a> 
           <!-- <a href="#search_results"
class="button add slideup">+</a>   -->
       </div> 
           <form id="search"> 
<ul class="rounded">
<li id="notice"> Type your search term below and hit search twitter</li>
<li>
<input type="text" id="keyword" name="keyword"
placeholder="type your search term here">
</li>
</ul>
<a href="#" class="whiteButton submit">SEARCH TWITTER</a> 
</form>
       </div> 
       </div> 
<div id="info">
<div class="toolbar">
<a href="#home" class="button leftButton flip">back</a>
<h1>TWIGLE BY mambenanje</h1>
</div>
<div>
<ul class='rounded'>
<li>mambenanje is CEO of AfroVisioN Group - www.afrovisiongroup.com<br />
And TWIGLE is a tutorial he did for packtpub.com</li>
<li>TWIGLE runs on iPhone and Android because its powered by jqtouch
and it helps users search twitter from their internet connected handhelds</li>
</ul>
</div>
</div>
<div id="search_results">
<div class="toolbar">
<a href="#home" class="button leftButton flip">back</a>
<h1 id="search_title">Search results</h1>
</div>
<div>
<ul class="rounded" id="results">
</ul>
</div>
</div>
</body>
</html>
[/code]

Thats the DOM structure for our application. Taking a close look at it,  you will see three main div siblings of the <body> tag. These divs represent the pages our application will have and only one of these divs appears at a time in a jQTouch application. Note the toolbar class that is called inside each of those divs to represent the app view's toolbar(title bar + menu) on every given page.

The <ul classs='rounded'> is also needed to represent rounded listed items typical for iPhone applications.

So in summary our application has three pages which would be home, info and search_results.

Lets explain the DOM for every page:

Home:

[code] 
<div id="home"> 
            <div class="toolbar"> 
                <h1>TWIGLE</h1> 
                <a href="#info" class="button leftButton flip">Info</a> 
                 <!-- <a href="#search_results"
class="button add slideup">+</a>   -->
            </div> 
            <form id="search"> 
<ul class="rounded">
<li id="notice"> Type your search term below and hit search twitter</li>
<li>
<input type="text" id="keyword" name="keyword"
placeholder="type your search term here">
</li>
</ul>
<a href="#" class="whiteButton submit">SEARCH TWITTER</a> 
</form>
            </div> 
        </div> 
[/code]

The home page has a toolbar that contains the TWIGLE heading, along with a jQTouch button that is left aligned and when clicked, flips to the next page which is Info. The other button which leads to the search_results page is commented out using html comments. Its there to show that you can add more buttons to the toolbar.

Next is the form which has the id:search. This is how jQTouch works with forms with no action or method. The form submission is done via javascript which will be explained later.

The rest is instruction and the keyword input field. Look closely at the search twitter button. Its not a typical input button, but an anchor tag styled with jQTouch theme classes that tells jQTouch this is a white button. It is responsible for initiating the form submission.

The home page is the most important page in this application as it contains the form and like every home page it is also the welcome page of the application.

The Info Page:

[code]
 
<div id="info">
<div class="toolbar">
<a href="#home" class="button leftButton flip">back</a>
<h1>TWIGLE BY mambenanje</h1>
</div>
<div>
<ul class='rounded'>
<li>mambenanje is CEO of AfroVisioN Group - www.afrovisiongroup.com<br />
And TWIGLE is a tutorial he did for packtpub.com</li>
<li>TWIGLE runs on iPhone and Android because its powered by jqtouch and
it helps users search twitter from their internet connected handhelds</li>
</ul>
</div>
</div>
[/code]

Its a tradition in software development to always have an about page for the software and iPhone/Android apps are no exception. The info page was created to give users of the twigle application an idea how this application came about. Closely look at the toolbar. It contains a button that leads to the home page and is styled to appear like a button. It flips to the home page when clicked.

The rest is just literature that is presented in rounded lists.

 

jQuery 1.4 Reference Guide This book and eBook is a comprehensive exploration of the popular JavaScript library
Published: January 2010
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:
        Read more about this book      

(For more resources, see here.)

The search_results page:

[code] 
<div id="search_results">
<div class="toolbar">
<a href="#home" class="button leftButton flip">back</a>
<h1 id="search_title">Search results</h1>
</div>
<div>
<ul class="rounded" id="results">
</ul>
</div>
</div>
[/code]

The search results page displays an empty list where in the results will be loaded dynamically using ajax from the backend.

We have reviewed the basic structure and seen how links or forms are created in HTML for jQTouch based applications.

Implementing the jQTouch javascript and styles:

We will now have to convert the above DOM structure in the index.html file into an application that looks and feels like a native iPhone application.

We do that by simply including the following code into the head tag as shown below:

[code] 
 <head> 
     <meta charset="UTF-8" /> 
     <title>Twigle &beta;</title> 
<!-- import the jqtouch css and theme -->
    <style type="text/css" media="screen">@import "./jqtouch/jqtouch.min.css";</style> 
    <style type="text/css" media="screen">@import "./themes/apple/theme.min.css";</style> 
<!-- import the jqtouch jquery and plugin files -->
   <script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="./jqtouch/jquery.1.3.2.min.js" type="text/javascript"
charset="utf-8"></script> 
   <script src='//dgdsbygo8mp3h.cloudfront.net/sites/default/files/blank.gif' data-original="./jqtouch/jqtouch.min.js" type="application/x-javascript"
charset="utf-8"></script> 
<!-- declare jqtouch startup params -->
<script type="text/javascript" charset="utf-8"> 
//initialize jQTouch and keep it in a var for future references
           var jQT=$.jQTouch({
                icon: 'icon.png',
                startupScreen: 'img/startup.png'
            });
</script>
</head>
[/code]

Adding the above code to the index.html line after line will produce the following effects:

Step one: the twigle interface with no style and no javascript

Step two: the figure below displays our twigle interface with no javascript but all the styles and theming in place. Hence you see the Home page, Info page and Search results page. In Step three when we add the javascript, only one of the pages below will appear.

Step three: This step is about interfacing twigle with styles and the javascript to initialize jQTouch functionality.

With the above code and steps, we finally transform our html DOM into an iPhone/Android application look-alike. But it doesnt yet work like an application. We need to add the following code to make the interface functional.

Edit the index.html file right below the initialization of the jQTouch, add the following code:

[code] 
<script type="text/javascript" charset="utf-8"> 
//initialize jQTouch and keep it in a var for future references
           var jQT=$.jQTouch({
                icon: 'icon.png',
                startupScreen: 'img/startup.png'
            });
$(document).ready(function(){
//set function to submit the search form
$('#search').submit(function(){
//grab the notice div so we can manipulate it
var notice=$('#notice');
//grab the notice instructions so we can reset
var noticetxt=notice.html();
//set notice to searching...
notice.empty().append('searching...');
//get the keywords
var query=$('#keyword').val();
//remove any # tag if any
query=query.replace('#','');
$('#search_title').empty().append('Search results for '+query);
//use ajax to load the twitter results
$.ajax({
 url: 'twigle.php?q='+query,
 success: function(data) {
$('#results').html(data);
jQT.goTo('#search_results','slide');
notice.empty().append(noticetxt);
 }
});
});
});
</script>
[/code]

Note that from our previous code, the code that is added starts with $(document).ready(function(){});. This is typical of every jquery based application or javascript code. This code gets executed when the page or application is finally loaded. It then implements listeners for the search button. Although the code is well commented, let's just briefly run through it once again.

The home page contains a form html tag with id:search. When the form has to be submitted, we use that id to refer to the form in the code. We also use the id when the home page search twitter button is clicked.

We then show notifications to user that the search is being carried out and the content is being loaded from twitter. This is also essential as without this, users might feel the application is not working.

We then sanitize the input basically to allow users to search for terms with hash tags(#) like #naijaborn in our twigle application.

Finally, we use the ajax plugin to load the twigle.php page with the query as a GET parameter which will then load the data and a series of list entries <li> tags that we set in the results DIV on the search_results page.

When the content is loaded from twigle.php back-end, we put it on the search_results page which is in same DOM, then navigate to the page pragmatically using jQT.GoTo(page,animation_to_page_style);

jQT is declared when we initialize jQTouch. Thats why in the code above, there is a comment that says "//initialize jQTouch and keep it in a var for future references". It is very important to have a singleton of the current jQTouch javascript object for custom page navigations, animations and more flexibility.

Clicking the search button, calls the backend, passes the keyword to it as a query and finally gets the results displayed in the search_results page.

Now that we have written the code to manipulate jQTouch pages, submit forms and do basic server side communication from our jQTouch based apps, let's see how the twigle.php backend works to finalise the application.

Edit the twigle.php and paste the following code into the file:

[code] 
<?php
//twitter search procedure for twigle
//this is the server side code of twigle, a jqtouch application
development tutorial by mambenanje
$tweetsData=file_get_contents("http://search.twitter.com/search.json?q=".$_GET['q']);
$tweets=json_decode($tweetsData);
if(count($tweets->results)>0){
foreach($tweets->results as $t){
echo "<li style='padding-left:60px; background-image:url(".$t->profile_image_url.");
background-repeat:no-repeat; height:40px;'>";
echo "<b>".$t->from_user.":</b>";
echo $t->text;
echo "</li>";
}
}else{
echo "<li> no tweets found matching that search term</li>";
}
?>
[/code]

The above code when called, loads the results from twitter search API remotely using the php function file_get_contents which is a lazy way of implementing CURL calls. It supports only GET. For something more robust, php CURL is advised.

When we get the results from twitter API, we decode it either from xml to php or from json to php depending on the request you passed to twitter. In our case we decode it from json data to a php results array with objects containing the individual tweets that match the query.

We then check if there are any results, loop through the results and display them as <li> entries to fit into our search_results page found in index.html.

And if there are no results, we return a list entry that states just that.

You can test the final application at http://www.afrovisiongroup.com/twigle or download the full source code here.

Summary

With jQTouch, you can develop native looking applications for the iPhone OS and the Android OS for your existing web solutions. You can definitely develop your next application with existing knowledge of javascript, html and jquery without going through the Android SDK or iPhone SDK. The development process can also be fully tested with any webkit enabled web browser on your computer. This means you can develop these application, test them on your windows/linux/etc machine using Chrome Browser or Safari, and it cuts you the stress of owning a Mac to do iPhone development along side helping you build one application for both Android and iPhone OS.


Further resources on this subject:


PHP jQuery Cookbook Over 60 simple but highly effective recipes to create interactive web applications using PHP with jQuery
Published: December 2010
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Mambe Nanje Churchill is a Cameroonian software entrepreneur based in Buea. He is the founder and president of AfroVisioN Group, a software company which provides domestic and outsourced solutions to a broad range of customers. When he is not writing software or doing some form of related business, you might find Churchill watching MTV or shooting and editing music videos.

Books From Packt

jQuery 1.4 Animation Techniques: Beginners Guide
jQuery 1.4 Animation Techniques: Beginners Guide

Learning jQuery 1.3
Learning jQuery 1.3

Joomla! 1.5 JavaScript jQuery
Joomla! 1.5 JavaScript jQuery

CMS Design Using PHP and jQuery
CMS Design Using PHP and jQuery

WordPress 3.0 jQuery
WordPress 3.0 jQuery

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

ColdFusion 9 Developer Tutorial
ColdFusion 9 Developer Tutorial

jQuery UI 1.7: The User Interface Library for jQuery
jQuery UI 1.7: The User Interface Library for jQuery

Your rating: None Average: 4.4 (7 votes)
good one by
good one
Good explanation by
Cool article. It helps me too much. Thanks Fernando Diaz Lima Peru
A very good insight by
Thank you very much, i just started looking for some infos on the web and this post of yours gave me a very good insight on JQTouch to begin with, thanks a lot.
code samples have too many typos by
documet vs document etc. Makes it hard to follow along. Please fix.
Thank you! by
Many many thanks for taking the time to write the article. I found it very helpful!
Thanks for the article by
Fantastic article, its my first exposure to building a jQTouch app. Now if I can only figure out how to host/run php files in node.js...
Excellent article by
Many thanks for putting the time in to give this intro to JQTouch
iPhone + PHP file by
How does the PHP file will execute in iPhone ????? Thanks Vasim Padhiyar

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
H
9
v
T
p
s
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software