Notice: Undefined index: order_next_posts in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 194

Notice: Undefined index: post_link_target in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 195

Notice: Undefined index: posts_featured_size in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 196
News

Build a Twitter app with jQuery Mobile

Create and code a Twitter feed app with the talented team at Studio Mohu

Build a Twitter app with jQuery Mobile

This article originally appeared in issue 179, you can download the project files here

jQuery needs little introduction, the JavaScript framework has dominated the world of front-end development for creating rich internet applications over the last four years. jQuery Mobile, now in alpha development, looks set to do the same for the rapidly emerging mobile market by building on top of jQuery’s solid foundations. In this tutorial we’ll dive right in and make a simple application pulling several Twitter feeds from topical websites that might be useful to a fledgeling web designer. jQuery Mobile comes with a bunch of interface themes and interactions which will allow us to rapidly deploy our app without getting bogged down in code.

jQuery Mobile does use progressive enhancement to ensure your app will work across a broad range of mobile devices. That said, for this tutorial we’ll be focusing on developing for the iPhone. We’ll be using HTML5, CSS and a sprinkling of PHP for grabbing and outputting the Twitter feeds. It’s useful to have a local development environment set up to view the results of the PHP files, but otherwise you can upload to your web hosting. It’s worth noting at this stage that jQuery Mobile is in alpha release so it might not be suitable for all project environments. Also, the full code for all the steps here can be found on the cover disc.

1) Set up index.php

Let’s dive right in and create an index.php file with the super-simple HTML5 doctype. For best practice declare your encoding as UTF-8 in the head and give your page a title of “Web Designer Feed”.

001 <!DOCTYPE html> 
 002 <html>
 003    <head>
 004       <meta charset=”UTF-8”>

2) Get jQuery

All it takes to add jQuery Mobile to your page is to create three links in your head to the jQuery Mobile CSS file and two JavaScript files. Grab the latest versions of jQuery and jQuery Mobile (as of writing these are jquery-1.4.3 and jquery.mobile-1.0a2 respectively). Luckily you don’t actually need to download these as jQuery provides hosted versions on its content delivery network.

001 <link rel=”stylesheet” href=”http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.css” />
 002 <script src=”http://code.jquery.com/jquery-1.4.3.min.js”></script>

3) Define page structure

jQuery Mobile responds to various data-role tags in your code to activate default framework behaviours. Define your page by creating a <div> tag inside the body tag with an attribute of data-role=”page”. You can create three more containers for your header, content and footer with their respective data-role attributes.

001 <div data-role=”page”>
 002    <header data-role=”header”>
 003    </header>

4) Add list content

Populate your page with some content. Add an h1 tag with your application name inside the header tags. In your content area create an unordered list with a data-role attribute of “listview”. Add some list-items of Twitter feeds with titles in h3 tags and a short description of the feed in paragraph tags.

001 <header data-role=”header”>
 002    <h1>Web Designer Feed</h1>
 003 </header>

5) Add links

Eventually you want each list item to link through to its relevant Twitter feed, so create some links inside each h3 tag. For each list item create a link to feed.php which you’ll create shortly. You want to pass a variable of the user name of each Twitter account which you can do using the GET method of submitting values via URL. At the end of each link add the variable twitterUser as shown in the code.

001 <li>
 002    <h3><a href=”feed.php?twitterUser=webdesignermag”>Web Designer Mag</a><h3>
 003    <p>Defining the internet through beautiful design</p><
 004    </li>

6) Spruce up the list

Divide your list into categories using list dividers and add some icons to each item. Between each group of list items add another list item with a data-role of “list-divider” and some descriptive text. Also add some image icons for each feed to add some visual appeal. For a full list of feeds and images grab the code contents from step06-complete.txt and the images folder on the CD.

001 <li data-role=”list-divider”>Publications</li>
 002 <li>
 003    <img src=”images/webdesignermag.png” alt=”Web Designer Mag”>

7) Add theme styles

jQuery Mobile comes with several themes out-of-the-box. Currently your app is using the default theme, so mix things up a bit. In your unordered list tag add attributes for data-theme and data-dividertheme. There are several to choose from ranging from “a” to “e”, We’ve gone for “c” and “a” respectively. Have a play around and see which themes work for you.

001 <ul data-role=”listview” data-theme=”c” data-dividertheme=”a”>

8) Style the images

Create a new mobile.css file and link to it within your index.php head. Add some good-looking styles to the images in your list. Add styles for width, height and margin so that they sit nicely centred within the list items. You can also add some rounded corners using border-radius.

001 ul li img{
 002    border-radius: 15px; 

9) Create feed.php

You need to create a page for pulling in each Twitter feed. Create a feed.php file and set it up with the same HTML5 doctype and head links to your CSS and JavaScript files as you’ve used in index.php. Create data-role containers for the header and footer, but this time just a blank div for the content (we don’t want jQuery Mobile to style this content).

001 <div data-role=”page”>
 002    <header data-role=”header”>
 003    </header>
 004  <div>
 005  
 006  <div>

10) Get Twitter user

In step five you added the twitterUser variable to each link on index.php. Using PHP grab that variable from the URL so your feed.php page will know which Twitter feed it should fetch. At the very top of your feed.php file above the DOCTYPE declaration add the following PHP code to grab the variable. You can default to webdesignermag when no Twitter user has been defined in the URL.

001 <?php
 002    $twitterUser = empty($_GET[‘twitterUser’]) ? ‘webdesignermag’ : $_GET[‘twitterUser’];
 003 X?>

11) Get Twitter feed

You can grab the latest Twitter timeline for a particular user as a JSON feed using PHP’s file_get_contents function combined with the twitterUser variable you have from the last step. Then using PHP’s in-built json_decode function you can turn the feed into an array of data which will be easier to deal with.

001 $json = file_get_contents(“http://twitter.com/status/user_timeline/$twitterUser.
 json”, true); //get the twitter JSON feed
 002 $result = json_decode($json); //json_decode content as array

12) Get the feed name
Your PHP $result variable now contains an array of each recent tweet containing various hierarchical objects of data. A full breakdown of decoding JSON feeds is beyond the scope of this tutorial, but what you are doing here is taking the first result from the ‘$result’ array which starts from number 0. Within that you are selecting the ‘user’ object and within that you are selecting ‘name’.

001 $feedName = $result[0]->user->name;

13) Output the feed name

Inside your header tags create a h1 tag and output the value of the feedName variable using the PHP echo function. This should now output the name of the Twitter user currently selected as it appears on their Twitter page.

001 <header data-role=”header”>
 002    <h1><?php echo($feedName) ?></h1>
 003 </header>

14) Get individual tweets

Create an empty unordered list tag with a class of “tweets” inside the empty div tag created in step nine. Add a PHP for loop to output each tweet from the $result array as an individual item. Use PHP echo to output opening and closing tags for each list item.

001 <ul class=”tweets”>
 002    <?php
 003    foreach ($result as $item) {
 004       echo(‘<li class=”ui-li”>’);

15) Set up tweet data

Inside the for loop and above the echo tags create variables for tweet text, time and date. You are using the same method from step 12 to drill down into each object array for the relevant content. For the tweet text you’re using PHP’s htmlentities function to output html-safe text from the tweet’s ‘text’ object. You’re then using PHP’s date function to turn the tweet’s ‘created_at’ date information into a readable date string.

001 $text = htmlentities($item->text, ENT_QUOTES, ‘utf-8’);
 002 $time = date(‘g:ia’, strtotime($item->created_at));

16) Output tweet data

Now create two more echo functions in-between the opening and closing list-item tags to output your tweet data. The first one outputs your tweet text and the second one combines the date and time variables to output when the tweet was published. If you check your page now you should see a list of tweets.

001 echo(‘<h3>’.$text.’</h3>’);
 002 echo(‘<p>Posted on ‘.$date.’ at ‘.$time.’</p>’);

17) Use regular expressions

Your tweet text is outputting nicely but it would be nice if URLs and other Twitter tags within the text were clickable links. You can achieve this using regular expressions (regex) which search for patterns in the text. You can add three regex commands above your echo functions to replace URLs, user names and Twitter tags with links.

001 $text = preg_replace(‘@(https?://([-w.]+)+(/([w/_.]*(?S+)?(#S+)?)?)?)@’, 
 ‘<a href=”$1”>$1</a>’, $text); //turn URLs into links 
002    $text = preg_replace(‘/@(w+)/’, ‘<a href=”http://twitter.com/$1”>@$1</a>’,
 003 $text);//turn twitter usernames into links

18) Style the tweets

Now add some CSS to make the tweets output consistently in style to your index.php content. Reset the margin and padding of the unordered list so that it sits flush with layout. Add a gradient background to the list items and add some font styles to the h3 and paragraph tags.

001 ul.tweets{ margin: 0; padding: 0; }
 002 ul.tweets li {
 003    padding: 0 15px 0 15px;

19) Create a custom header

To personalise the homepage a bit create a custom masthead graphic. You need to create two versions, one for 3G iPhones which will be 320px wide by 75px named header.png and one for the new retina displays which will be 640px wide and 150px tall named header@2x.png. You can use any graphics editing tool of your preference here. We’ve used Fireworks in this instance and exported as a transparent PNG so the background gradient will show through.

20) Add the header CSS

In index.php add an id of “masthead” to the header tag. Then in your mobile.css file add the following styles to hide the text and replace it with your custom header graphic. Using the @media declaration you are able to target retina displays and serve up your higher resolution header graphic.

001 header#masthead h1{
 002    background: url(images/header.png) 0 0 no-repeat;
 003    width: 100%;

21) Add a dashboard icon

You’re basically there, but a nice touch is to add an icon which will display on the iPhone dashboard when the app is bookmarked in Safari. Create an icon in your preferred graphics editor sized 129px by 129px. To add this icon to the app simply add the code within the head tags of both your pages.

001 <link rel=”apple-touch-icon-precomposed” href=”images/dashboard-icon.png” /

22) Link back to your portfolio

Your app is complete, but why not add a link in the footer back to your portfolio for a bit of self-promotion. Add the link code inside the footer data-role div and jQuery Mobile will automatically style it up as a button for you. Now it’s just time to upload your app and navigate to it in Safari mobile on your iPhone.

001 <footer data-role=”footer”>
 002    <h4><a href=”http://www.studiomohu.com” rel=”external”>Developed by Mohu&trade;</a></h4>
 003 </footer>
×