facebook google plus twitter
Webucator's Free jQuery Mobile Tutorial

Lesson: Getting Started with jQuery Mobile

Welcome to our free jQuery Mobile tutorial. This tutorial is based on Webucator's jQuery Mobile course.

In this lesson, we'll cover how to set up a basic jQuery Mobile page: how to include needed pages, create markup for a basic page, link to pages, and create transitions.

Lesson Goals

  • Learn how to include needed JavaScript and cascading stylesheet files.
  • Learn what a basic jQuery Mobile page template looks like.
  • Learn how jQuery Mobile manages transitions between same-site and external pages.
  • Learn how page transitions work.
  • Learn how to add and style buttons.
  • Learn when and how to use dialogs.

A Basic Page Template

To start using jQuery Mobile, you'll need to include three files in your page:

  1. The jQuery JavaScript file.
  2. The jQuery Mobile JavaScript file.
  3. The jQuery Mobile CSS file.

Optionally, you might include a jQuery Mobile theme CSS file; more on this later.

You can either link to files you download from the jQuery Mobile website or link to files hosted on various Content Delivery Networks, or CDNs. To create a standalone jQuery web application you would need to download the files to your local site, as would also be true if you were hosting a site to be accessed by users without direct access to the internet. In other cases, using the CDN-hosted files makes the most sense: a network of high-speed servers delivers files very quickly and efficiently, and this strategy makes it easier for you to update to newer jQuery or jQuery Mobile file versions in the future.

Whichever strategy you choose, hosting the files on your own web server or linking to CDN-hosted files, be sure to choose the minified versions of the files for production use. The minification (the removal of spaces and line breaks) makes these files smaller and, thus, reduces download time.

Here is an example of the code that would live in the head section of your pages, showing links to CDN-hosted files:

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

You could, if you wished, link the JavaScript and CSS files shown above in any web page and start making use of jQuery Mobile's functionality. Most of the time, however, you will want to structure the markup of your pages to conform to jQuery Mobile's conventions

Let's look at a first demonstration of some of these concepts. Nan & Bob's is a (fictional) small bookstore and cafe, located right in the middle of downtown. We have developed a mobile website for them - using jQuery Mobile, of course - that we'll be extending and enhancing throughout this course. The site will give users information about their store, their books, and their cafe.

Open the file GettingStartedjQuery/Demos/basicpagetemplate/index.html in a mobile browser and also in a file editor to check out the code. Not much there yet - the page looks something like this when viewed on a mobile device:

basic page template

Let's review the code:

Code Sample:

GettingStartedjQuery/Demos/basicpagetemplate/index.html

The doctype at the top of the page identifies this page as an HTML5 page. As discussed above, we link to (and thus get to use all the power of) jQuery and jQuery Mobile JavaScript and CSS files in the head of the document.

In the body of the page, you'll note that the content of the page is marked up by a div with the data-role="page" attribute. jQuery Mobile makes extensive use of HTML5 attributes, with data-role among the most important. This simple example displays only one page; we'll see soon that we can offer our users multiple pages as multiple html files or within one single file.

Within the page div, we see data-roles for header and footer - which are, unsurprisingly, the header and footer of this particular page.

Let's now get you started writing some code!

A Basic Page Template

You could, if you wished, link the JavaScript and CSS files shown above in any web page and start making use of jQuery Mobile's functionality. Most of the time, however, you will want to structure the markup of your pages to conform to jQuery Mobile's conventions

Let's look at a first demonstration of some of these concepts. Nan & Bob's is a (fictional) small bookstore and cafe, located right in the middle of downtown. We have developed a mobile website for them - using jQuery Mobile, of course - that we'll be extending and enhancing throughout this course. The site will give users information about their store, their books, and their cafe.

Open the file GettingStartedjQuery/Demos/basicpagetemplate/index.html in a mobile browser and also in a file editor to check out the code. Not much there yet - the page looks something like this when viewed on a mobile device:

basic page template

Let's review the code:

Code Sample:

GettingStartedjQuery/Demos/basicpagetemplate/index.html

Code Explanation:

The doctype at the top of the page identifies this page as an HTML5 page. As discussed above, we link to (and thus get to use all the power of) jQuery and jQuery Mobile JavaScript and CSS files in the head of the document.

In the body of the page, you'll note that the content of the page is marked up by a div with the data-role="page" attribute. jQuery Mobile makes extensive use of HTML5 attributes, with data-role among the most important. This simple example displays only one page; we'll see soon that we can offer our users multiple pages as multiple html files or within one single file.

Within the page div, we see data-roles for header and footer - which are, unsurprisingly, the header and footer of this particular page.

Let's now get you started writing some code!

Nan & Bob's Online

Duration: 10 to 15 minutes.

Nan & Bob want to boost their online presence with a new, also mobile-optimized, site to sell books online. You'll build a very basic shell - a first page - for that site now.

  1. Open GettingStartedjQuery/Exercises/nanandbobonline.html in a file editor.
  2. Add links to CDN-hosted jQuery Mobile CSS, jQuery JavaScript, and jQuery Mobile JavaScript files in the head of the file.
  3. In the body of the document, add markup for the page and for the header, main content, and footer.
  4. Test the file by viewing in a mobile browser; the results should look like this: Nan & Bob's online screenshot

Challenge

We can (and usually do) add CSS to our jQuery Mobile pages to style the look and feel of our work. Try adding some custom CSS - a <style> tag in the head of the page - to change the look of some aspect of an element on the page. Your solution might look something like shown below, where we've changed the font face (to "Georgia") and size (a little bigger) for the paragraph in the main body of the page:

Nan & Bob's online screenshot

Solution:

GettingStartedjQuery/Solutions/nanandbobonline.html
            

We link to the various CSS and JavaScript files from the code.jquery.com and ajax.googleapis.com CDNs. We add markup for the canonical jQuery Mobile page structure: a div with data-role="page" and divs for the header, main content, and footer.

Challenge Solution:

GettingStartedjQuery/Solutions/nanandbobonlineadvanced.html
            

The only difference in the challenge solution is the addition of a style rule in the head of the document, assigning font-family:Georgia and font-size:1.5em for the paragraph contained in the main body of the page.

Linking between Pages

The concept of a "page" in jQuery Mobile can be a slippery one. As users of a site, we know what pages are: we tap on a button or link and the stuff displayed on our phone changes - a new title and different content makes it clear that we have left one page for another page.

In traditional web development, this process of linking between pages would usually mean linking between two files: a page index.html might include a link (an a tag) to about.html. The user clicks the link for about.html, which sends a request from his/her browser to the server, which sends back a response with the contents of about.html.

With jQuery Mobile, "pages" might be multiple divs - each with the data-role="page" attribute - in the same file. Those pages might also be separate files. And any link on our jQuery Mobile pages could, of course, link to an external site like google.com.

Let's look at an example. Open up GettingStartedjQuery/Demos/nanandbobs/index.html in a mobile browser and in a file editor to review the code. The first page looks as follows:

multiple pages

Code Sample:

GettingStartedjQuery/Demos/nanandbobs/index.html

Code Explanation:

The four pages - "Home", "Cafe", "Books", and "Contact" - correspond to the four divs, each with data-role="page", in the file index.html. Each page div has its own header, content, and footer. We've used jQuery Mobile's navbar UI widget to display the navigation links, and chosen simple icons to represent each of the four pages. We'll get more into more detail about this (and other) UI widgets, as well as custom icons, down the road.

Note the correspondence between the id value of each page div and the links:

  1. <a href="#home"> links to the Home page, which has id "home".
  2. <a href="#cafe"> links to the Cafe page, which has id "cafe".
  3. <a href="#books"> links to the Books page, which has id "books".
  4. <a href="#contact"> links to the Contact page, which has id "contact".

Note that the appropriate title (from the data-role="header" div) shows for each page and that all other content - the navbar items, main content, etc. - displays for each page. There is just one file (index.html) here, but the multiple divs act just like four separate pages as far as the user is concerned.

We use the data-iconpos attribute to position the icons, in this case to "top", above the text. Other valid values are "bottom", "right", or "left". We apply a class of "ui-btn-active ui-state-persist" to show the relevant icon as highlighted for each given page. The latter class, ui-state-persist, ensures that the current nav element should remain highlighted even if the page is reloaded by the user.

Ajax Navigation System

For devices that support it, jQuery Mobile links between pages via Ajax; for examples like the previous one, where multiple "pages" are housed in one physical file, this means we save extra (and more costly, in terms of speed) http requests. The beauty of the framework is that you don't need to worry about the low-level stuff: you link between pages as you normally would, and jQuery Mobile automatically handles page requests in a single-page model, using Ajax when possible. The Ajax page transitions also enable our use of a variety of cool visual transitions between pages. If Ajax isn't possible, or if you specify that you don't want Ajax, a normal http request is used instead.

Some links won't be loaded with Ajax but instead will cause a full page refresh (see table below):

Links without Ajax
Description Example
Links that point to other domains <a href="http://www.google.com/">google.com</a>
Links with rel="external" <a href="index.html" rel="external">somepage.html</a>
Links with data-ajax="false" <a href="index.html" data-ajax="false">aboutus.htm</a>
Links with target attribute <a href="index.html" target="_blank">books.php</a>

Page Transitions

Depending upon the device you are using, you might have noticed a slight fade-in/fade-out effect when transitioning between pages in the last example. By default, jQuery Mobile applies a "fade" transition between Ajax-loaded pages. Pages that aren't loaded via Ajax aren't loaded with an animated transition. The framework offers a variety of page transitions from which to choose:

jQuery Mobile Transitions
Transition Description
fade Cross-fade animation; the default transition
pop New page grows from small to big
flip A rotation animation, spinning on center vertical axis
turn A rotation animation, like a page turn
flow Current page shrinks off to left; new page slides in from right
slidefade New page slides and fades in from right
slide New page slides in from right
slideup New page slides up from bottom
slidedown New page slides down from top

You can override the default (fade) transition for all transitions in the given file by adding a global configuration directive to the head of the file after linking the jQuery JavaScript file but before linking the jQuery Mobile file:

<script>
$(document).on("mobileinit", function(){
	$.mobile.defaultPageTransition = 'flow';
});
</script>

You can also specify a particular transition for a given link with the data-transition attribute:

<a href="index.html" data-transition="flip">I will flip</a>

Let's work on these concepts by building out some pages for the Nan & Bob's Online site.

More Pages & Transitions for Nan & Bob's Online

Duration: 20 to 30 minutes.

In this exercise, you will add a top navbar to the Nan & Bob's Online site, build new pages for "Books" and "Contact", and set specific page transitions. The solution should look something like this:

Nan & Bob Online - more pages

  1. Open GettingStartedjQuery/Exercises/transitions.html in a file editor.
  2. Add a div with data-role="navbar" to the header of the page div in the exercise file.
  3. Add links within the navbar to #home, #books, and #contact.
  4. From the jQuery Mobile docs, choose appropriate icons for each link; use the data-icon attribute on the a tag to specify the icon.
  5. Copy the existing page div and paste two new copies; change one pasted copy to become the "Books" page and the other to become the "Contact" page. Be sure to set the id of each page div appropriately.
  6. Set the transition from "Books" to "Home" and from "Contact" to "Home" to be the slideup transition.
  7. Use $.mobile.defaultPageTransition in the head of the document to set the default page transition to flip.
  8. Test your work by viewing the pages in a mobile browser.

Solution:

GettingStartedjQuery/Solutions/transitions.html

Code Explanation:

We use $.mobile.defaultPageTransition = 'flip'; to set the default page transition to flip in a script block in the head of index.html; note that the script comes after we link the jQuery library but before we link jQuery Mobile.

We add a navbar to the #home div with links to #home, #books, and #contact.

We add two new divs with data-role="page", one each for the #books and #contact pages.

We set, using data-transition="slideup", a custom page transition between the #books and #home pages and between the #contact and #home pages

Buttons

Simple inline text links can be a challenge for users on a mobile device. Buttons, easier to see and easier to tap, work better for most links. jQuery Mobile makes it easy to present a-tag links as buttons in a variety of styles.

To present a link as a button, simply add the class class="ui-btn" to the a tag:

<a href="#" class="ui-btn">Button</a>

You can style buttons as mini, presenting them slightly smaller, by adding the class ui-mini. Classes ui-corner-all and ui-shadow add rounded corners and a drop shadow, respectively, to the button. Adding class ui-btn-inline presents the button inline - just wide enough for its label text - rather than spanning the full width of its parent element.

Adding and positioning icons is quite easy: simply add the relevant class:

  1. ui-btn-icon-left
  2. ui-btn-icon-right
  3. ui-btn-icon-top
  4. ui-btn-icon-bottom

Class ui-btn-icon-notext presents the button with just the specified icon and no text label.

You can create and use your own custom icons; jQuery Mobile offers a set of stock icons:

jQuery Mobile Button Icons
Icon Code
Action Icon action
Alert Icon alert
Arrow-D Icon arrow-d
Arrow-D-L Icon arrow-d-l
Arrow-D-R Icon arrow-d-r
Arrow-L Icon arrow-l
Arrow-R Icon arrow-r
Arrow-U Icon arrow-u
Arrow-U-L Icon arrow-u-l
Arrow-U-R Icon arrow-u-r
Audio Icon audio
Back Icon back
Bars Icon bars
Bullets Icon bullets
Calendar Icon calendar
Camera Icon camera
Carat-D Icon carat-d
Carat-L Icon carat-l
Carat-R Icon carat-r
Carat-U Icon carat-u
Check Icon check
Clock Icon clock
Cloud Icon cloud
Comment Icon comment
Delete Icon delete
Edit Icon edit
Eye Icon eye
Forbidden Icon forbidden
Forward Icon forward
Gear Icon gear
Grid Icon grid
Heart Icon heart
Home Icon home
Info Icon info
Location Icon location
Lock Icon lock
Mail Icon mail
Minus Icon minus
Navigation Icon navigation
Phone Icon phone
Plus Icon plus
Power Icon power
Recycle Icon recycle
Refresh Icon refresh
Search Icon search
Shop Icon shop
Star Icon star
Tag Icon tag
User Icon user
Video Icon video

To style a link button with a given icon, use the corresonding class. For instance, a button with a "star" icon would be coded as follows:

<a href="#" class="ui-btn ui-btn-icon-left ui-icon-star">Button with Star</a>

where the star portion of the class ui-icon-star specifies the "star" icon.

As we mentioned above, buttons can display with no text (with class ui-btn-icon-notext) and display inline. Let's look at some examples of these features:

Buttons

Code Sample:

GettingStartedjQuery/Demos/buttons/index.html

Code Explanation:

  1. The "Generic Button" is simply a link (an a tag) with class ui-btn.
  2. The "Mini Button" has class ui-mini, which causes the button to display with less top and bottom padding.
  3. The "Delete" button's class ui-icon-delete adds the stock jQuery Mobile "delete" icon, positioned at left.
  4. The "Search (bottom)" button presents the jQuery Mobile "search" icon; class ui-btn-icon-bottom positions the icon at bottom.
  5. The class ui-btn-icon-notext on the next button hides all label text, showing just a stock "home" icon.
  6. The two icons at bottom make use of the class ui-btn-inline attribute, preventing them from filling the horizontal width of the page; both are also "mini" because of the presence of class ui-mini

Grouped Buttons

Containing a set of buttons in a div element with the attribute data-role="controlgroup" groups the contained buttons visually, either stacked vertically (the default) or horizontally (with the additional attribute data-type="horizontal" on the container div):

Grouped Buttons

Code Sample:

GettingStartedjQuery/Demos/buttons/grouped.html

Code Explanation:

The first set of buttons stacks vertically because of the <div data-role="controlgroup"> wrapping the three buttons. The data-type="horizontal" on the second set of buttons aligns the buttons horizontally. The third set of buttons ("Left" and "Right") include appropriately labeled and positioned icons.

Dialogs

We can present content in jQuery Mobile as a modal dialog - content popped up in front of the current page, like a dialog box - by adding attribute data-dialog="true" to a given page. With the "dialog" attribute, the linked-to content has styles (rounded corners, margins around the page, a drop shadow) to make it look like it is above the current page. We can use dialogs to present modal information (i.e., "confirm delete"), offer associated content, present signup forms, etc.

The left screenshot shows the calling page; the right screenshot shows the popped-up dialog the results from tapping the "Dialog" link:

dialog demo

Code Sample:

GettingStartedjQuery/Demos/dialogs/index.html

Code Explanation:

The data-dialog="true" attribute on the #dialog page presents the linked-to content - the div with id "dialog" - as a dialog. The popped up content ("I'm a dialog") thus opens with a "close" button at upper left and drop shadowing to make it appear above the existing page content.

Buttons & Dialogs for Nan & Bob's Online

Duration: 20 to 30 minutes.

In this exercise, you will use what we have learned about buttons and dialogs to further flesh out the content on the Nan & Bob's Online site.

  1. Open GettingStartedjQuery/Exercises/dialogs.html in a file editor.
  2. Add a button from the home page to a join-mailing-list dialog.
  3. Add a div (with data-role="page") for the mailing list signup form.
  4. Add a simple form, with input of type email, to the mailing list dialog page; you need not handle the processing of the form submission.
  5. The home page and mailing list dialog should look like this: mailing list dialog
  6. Add a button from the contact page to a dialog showing driving directions.
  7. Add a div (with data-role="page") for the directions dialog.
  8. The contact page and directions dialog should look like this: directions dialog
  9. Test your work from a mobile browser.

Solution:

GettingStartedjQuery/Solutions/dialogs.html

Code Explanation:

We add two buttons to the content of the existing pages: a button from the home page to the mailing list dialog and a button (with icon) from the contact page to the directions dialog.

When linked to, both the mailing-list-signup and directions content show as dialogs, because the data-dialog attribute for each has value true.

The mailing list dialog presents a simple email-list signup form, with an input of type email. The directions dialog offers the user some driving directions as simple text content.