facebook google plus twitter
Webucator's Free jQuery Mobile Tutorial

Lesson: What Is jQuery Mobile?

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

In this lesson, we will take a first look at jQuery Mobile: what it is, how it works, and how to begin building mobile-optimized web pages with it.

Lesson Goals

  • Learn what jQuery Mobile is, and isn't.
  • Learn about jQuery Mobile's support for various devices and browsers.
  • Learn how jQuery Mobile adopts the progressive enhancement strategy.
  • Learn how jQuery Mobile offers support for accessibility.
  • Learn how new features from HTML5 and CSS3 apply to mobile web development.

Introducing jQuery Mobile

We as web developers and designers have always wrestled with the challenge of meeting the diverse needs of users who view our work on many different devices. Internet Explorer might render a page differently from Firefox or Opera - and don't forget to account for older versions of the same browser. Connection speeds, screen resolutions, operating systems, use of screen readers - our code must work for all cases.

The explosive proliferation of smartphones and tablets over the past few years has added to our challenge. Screens are smaller, to be sure, and the differences between devices are greater than ever - and those devices come with new capabilities we didn't see on desktops and laptops. Wouldn't it be nice if the code we write for a given web page worked for a new Kindle Fire, an iPad, and an Android phone? And if we could exploit the device's orientation, GPS, and accelerometer?

jQuery Mobile is a tool to address these challenges. It is a user-interface framework, built on top of the jQuery JavaScript framework. jQuery Mobile offers a "unified user interface system that works seamlessly across all popular mobile device platforms, built on the rock-solid jQuery and jQuery UI foundation." For us, that means we can write code that will work consistently for lots of devices, address the unique challenges of smartphones and tablets, and leverage new device capabilities.

For this course, we will be working with jQuery Mobile version 1.4.5, the current stable version. Please note that future versions may change some of the API.

What jQuery Is Not

Keep in mind that jQuery Mobile isn't "jQuery for mobile". It isn't a replacement for the jQuery library for mobile use; rather, it is a user-interface library built on top of jQuery. You must include jQuery, as well as the jQuery Mobile stylesheet, to exploit its capabilities.

Does jQuery Mobile work for all devices - desktop, tablet, and mobile? jQuery Mobile is certainly more mobile-centric than most other frameworks; you'll have to decide if it works best for your site or application on desktops as well. Sites built with jQuery Mobile will certainly work on desktops; the library has been tested on all major desktop browsers. jQuery UI is a similar user-interface library for desktops, also built on top of jQuery. Learn more at jqueryui.com.

jQuery Mobile also isn't an SDK to leverage native phone capabilities. While we can access a fair bit of most phone's capabilities via JavaScript (and, thus, jQuery Mobile) - we can grab the user's position via GPS, present different content based on the phone's orientation, or track motion through the accelerometer - we are still using jQuery Mobile to build web pages, not native phone apps.

Supported Platforms

jQuery Mobile offers support for a wide range of platforms; they categorize browsers according to A-, B-, and C-level groupings, as below. A-level browsers can exploit full functionality (though, as the docs note, the "visual fidelity of the experience and smoothness of page transitions are highly dependent on the CSS rendering capabilities of the device and platform so not all A grade experience will be pixel-perfect but that's the nature of the web." See the jQuery Mobile docs for the current full list of supported devices.

jQuery Mobile Graded Browser Support
Browser Grade Details
A-grade Full enhanced experience with Ajax-based animated page transitions
B-grade Enhanced experience except without Ajax navigation features
C-grade Basic, non-enhanced HTML experience that is still functional

Progressive Enhancement & Responsive Web Design

Progressive Enhancement is a web-design strategy in which newer devices/browsers/capabilities receive an enhanced version of our pages, while less capable devices/browsers still receive basic content and functionality. Progressive Enhancement emphasizes semantic markup, controlling presentation with external stylesheets, and use of JavaScript to add functionality.

As the docs state, jQuery Mobile adopts a strategy of "starting with semantic HTML which will work on any device, then unobtrusively layering in advanced CSS and JS only for capable browsers. This provides a solid foundation for the device-level optimizations that RWD provides and is how the jQuery Mobile library is built." High-functioning devices and browsers get the good stuff - Ajax page transitions, native-app-like functionality, the "full enhanced experience" - while older or less capable devices and browsers still work, to the degree available. That's a huge help to us as developers: we can exploit new features and cool device capabilities without alienating users with older, less capable devices.

Responsive web design is an approach that aims to present web pages optimally given that capabilities of the device: a wider design for desktops might be narrower for smartphones with a narrower viewport. As the docs state, "jQuery Mobile has always been designed to work within a responsive context.... All the widgets are built to be 100% flexible in width to fit easily inside any responsive layout system...." See http://demos.jquerymobile.com/1.4.5/rwd/ for more information.

Accessibility Support

Web accessibility refers to the process of making websites usable for people who employ screen readers and other assistive technologies. A person with limited or no sight might, for example, uses the iPhone's VoiceOver to read aloud the contents of a web page.

With its focus on standard, semantic markup, jQuery Mobile provides a solid foundation for creating accessible sites. For newer browsers, many jQuery Mobile components "leverage techniques such as focus management, keyboard navigation, and HTML attributes" specified by accessibility standards.

A First Example

Let's take a first look at some code. When viewed on a smartphone, the page WhatIsjQueryMobile/Demos/helloworld/index.html looks something like this:

screenshot: Hello World on an iPhone

Open the page in a desktop browser and with a smartphone or emulator. Open up the page in a file editor, too, to check out the code.

Code Sample:

WhatIsjQueryMobile/Demos/helloworld/index.html
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>jQuery Mobile: Hello World</title>
		<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>
	</head>
	<body>
		<!-- the "page" div is the basic unit of jQuery Mobile - a page for the user -->
		<div data-role="page">
			<!-- this is a header, appearing at the top of the page -->
			<div data-role="header" data-position="inline">
				<h1>Hello World</h1>
			</div>
			<div class="ui-content" role="main">
				<p>A first jQuery Mobile page.</p>
				<!-- this is a button -->
				<a href="http://api.jquerymobile.com/" class="ui-btn">Home</a>
			</div>
		</div>
	</body>
</html>

Code Explanation:

While we'll get into lots more detail about code later in this course, we can point out a few things now. First, note that the page is a valid HTML5 document. The DOCTYPE is html. Some divs on the page make use of the HTML5 data attribute. The outermost div, for instance, has attribute data-role="page", which is significant for jQuery Mobile; we'll learn later in the course about divs as pages.

Second, note that the page links to some external resources - the two JavaScript files and one stylesheet are hosted at code.jquery.com, with nothing other than "index.html" on our end.

Let's check jQuery Mobile's progressive enhancement features. Consider the following two screenshots, each showing WhatIsjQueryMobile/Demos/helloworld/index.html in Google Chrome on a Mac:

screenshot of index.html with and without JavaScript

The top screenshot, with JavaScript on, shows a page similar to the smartphone view. The bottom screenshot shows that the page still works without JavaScript enabled: some of the styling is different, but the content is visible and the link works for users who don't have, or who have turned off, JavaScript.

Let's take a look at a quick first example - open up WhatIsjQueryMobile/Demos/html5/index.html in a browser and in your file editor to inspect the code. From a desktop browser you'll see something like this:

Basic HTML5 page

Code Sample:

WhatIsjQueryMobile/Demos/html5/index.html
<!doctype html>
<html>
<head>
   <title>A Simple Document</title>
</head>
<body>
  <header>
    <h1>Site Title</h1>
      <nav>
        <ul>
          <li><a href="#">link 1</a></li>
          <li><a href="#">link 2</a></li>
          <li><a href="#">link 3</a></li>
        </ul>
      </nav>
  </header>

  <section>
    <article>
      <h1>Page Title</h1>
      <h2>Subtitle</h2>
      <p>Content content content</p>
    </article>
  </section>
  <aside>
    <p>Sidebar info goes here</p>
  </aside>
  <footer>Footer content here</footer>
</body>
</html>

Code Explanation:

Presentationally, the page is less than stunning when viewed in a browser - we've not styled the elements at all - but the interesting bits are how we've marked up the content. Firstly, note that we've declared a doctype of html - this fact alone means this page is an HTML5 document.

Secondly, note that we have made use of the HTML5 semantic tags to imply meaning to the content we markup for viewing on the web:

  1. A header tag wraps the header of the page.
  2. The main navigation items are wrapped with a nav tag.
  3. An article tag wraps the main content, while an aside tag wraps the sidebar content.

jQuery Mobile WYSIWYG Builder

Intel Open Source Technology Center's Rapid Interface Builder is a what-you-see-is-what-you-get UI tool, allowing you to create pages from a drag-and-drop interface and, when finished, to download the resulting code. Visit the Rapid Interface Builder (note that you will need to use the Chrome browser) to try it out:

Intel RIB

Select some options from the top menu, drag to the screen, set text, or configure as needed, and voila: clicking the Export button at upper right offers you a well-formed template making use of jQuery Mobile's canned UI elements.

Building Your First jQuery Mobile Page

Duration: 10 to 20 minutes.

In this exercise, you will build a simple page using the Rapid Interface Builder.

  1. Visit the Rapid Interface Builder from a Chrome browser;
  2. When prompted, click OK to allow 01.org to "store large data on your computer" - the prototyping tool uses local storage to save your work on your browser;
  3. Edit the "Header" and "Footer" titles (by double-clicking on them) to present appropriate content - we used "Webucator" as the header and "jQuery Mobile" as the footer;
  4. Drag a button to the center pane of the layout window - link the button to http://api.jquerymobile.com/ and change the title of the button to "jQuery Mobile Docs";
  5. Optionally, change the "theme" property of any element (or all elements) to see how using the stock jQuery Mobile themes - lettered from "a" to "e" - to change the appearance of your page; we used the "e" theme;
  6. When you are satisfied with your page, click Preview at upper left to view your design - you can switch between "Layout" and "Preview" mode to make and view changes;
  7. Click Code at upper left to view the code that rendered your final design.
  8. Click Export at upper right to export (choose "zip" format) a copy of the finished project; if possible, save the project files to a web-accessible server and view on a smartphone to test it out with an actual mobile device;
  9. Open the file in an editor to check the code.
  10. The page should look something like this when viewed on a smartphone: UI Builder solution

Solution:

WhatIsjQueryMobile/Solutions/index.html
<!DOCTYPE html>
<html>
    
    <head>
        <title>title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="lib/jquery-1.6.4.js"></script>
        <script src="lib/jquery.mobile-1.1.0.js"></script>
        <link href="src/css/jquery.mobile.structure-1.1.0.css" rel="stylesheet">
        <link href="src/css/jquery.mobile.theme-1.1.0.css" rel="stylesheet">
    </head>
    
    <body>
        <div data-role="page" id="page1">
            <div data-role="header" data-theme="e">
                <h1>Webucator</h1>
            </div>
            <div class="ui-content" role="main">
                <a data-role="button" href="http://api.jquerymobile.com/" data-rel="page" data-theme="e">jQuery Mobile Docs</a>
            </div>
            <div data-role="footer" data-theme="e">
                <h1>jQuery Mobile</h1>
            </div>
        </div>
    </body>

</html>

We didn't have to write any code here - the Rapid Interface Builder prototyping tool generated all of the code for us.

As you dig through the code from our solution, note that we used theme "e" for all elements, giving the header, footer, and button a yellow color scheme - we'll dig deeper into themes later in this course.

Note, too, that the Rapid Interface Builder gathers together all of the files we need for our mobile-optimized page into directories: source for the jQuery and jQuery Mobile libraries, etc.

Last, note that the version of jQuery Mobile used by the Rapid Interface Builder tool is a bit outdated. While the tool is a nice way to start playing with jQuery Mobile in a visual way, we won't be using it going forward: we'll code pages by hand from here on out.

HTML5

HTML5 is the latest revision of the web markup language standard - it addresses the shortcomings of HTML 4 and XHTML, and also adds new features. Adoption of HTML5 depends, of course, on the degree to which browsers support HTML5 features. Luckily for us, support - especially for the features we'll focus on here - is especially strong among mobile browsers.

HTML5 is in part an acceptance of the fact that browsers tolerate lots of bad code, that perhaps we need not be so strict with requiring end tags and case sensitivity, and that making obsolete some ten years' worth of existing web pages would be catastrophic.

As an example of this flexibility, all of the following are permitted in HTML5:

  1. <link type="text/css" href="style.css" />
  2. <LINK TYPE="text/css" HREF="style.css" />
  3. <link type=text/css href=style.css>
  4. <LINK TYPE=text/css HREF=style.css>
  5. <LiNk TyPe=text/css hReF="style.css">

As the above shows:

  1. HTML5 is case insensitive.
  2. HTML5 allows for unclosed tags, but you can use the XML-style shortcut close tag if you want, as shown in the first two examples above.
  3. HTML5 does not require quotes around attribute values unless the values have spaces in them - <div class="news featured">, for example.

This new flexibility could lead to a bit of chaos on your development team. Different HTML authors will take different approaches. Our recommendation is that you choose one approach and stick to it. In this course, for example, we use the following guidelines:

  1. Write tags and attributes in all lowercase letters (even event handlers like onclick).
  2. Do not use shortcut close tags for void/empty elements.
  3. Put all attribute values in quotes. (Why? Because attribute values that have spaces in them have to be in quotes. And I do not like the idea of having some attributes in quotes and some not.)
  4. Minimize attributes when you can.

Of course, your choices here must also take into account your expected audience's use of older browsers - a self-closed div, for instance, won't work in Internet Explorer 7 and 8.

New HTML5 Features

The table below shows the new elements that HTML5 has introduced. Note that we won't cover most of these in this course.

New HTML5 Elements
Tag Description
<article> For a standalone article on a page. Articles can be nested within other articles; for example, a blog post would be contained in <article> tags and each comment would be contained within a nested <article> tag.
<aside> For content contained in an aside. Often used for navigation elements or for a list of articles or categories (e.g., in a blog).
<audio> For embedding audio files.
<canvas> For creating drawings natively in the browser.
<command> For command buttons similar to what you might see in the Microsoft Office 2010 ribbon. <command> must be nested in <menu>.
<datalist> For a drop-down list providing built-in functionality similar to a JavaScript autocomplete boxes.
<details> For expandable (usually initially hidden) content to provide more information about an element.
<embed> For backwards compatibility with the nonstandard (but well supported) <embed> tag in HTML 4.
<figcaption> For captions on images. (In HTML 4, there was no way to semantically associate a caption with an image.
<figure> For wrapping embedded content (e.g., an image) with a <figcaption>.
<footer> For the footer of a page or a section.
<header> For the header of a page or a section.
<keygen> For a generated key in a form.
<mark> For showing marked (or highlighted) text. Unlike <strong> or <em>, <mark> doesn't give the text any special meaning. The best example is marking a word or phrase that a user has searched on within the search results.
<meter> For a measurement within a set range.
<nav> For holding a group of navigation links.
<output> For holding output (e.g., produced by a script).
<progress> For a progress indicator (e.g., for a loading graphic).
<rp> Used within <ruby> tags to tell browsers that cannot render the East Asia characters properly what extra characters (usually parentheses) to display.
<rt> Used within <ruby> tags to show how to pronounce East Asia characters.
<ruby> For ruby annotations. (See http://www.w3.org/TR/ruby for examples.)
<section> For creating a <section> on the page. This helps the browser (user agent) determine the page outline.
<source> For indicating media sources within <video> and <audio>.
<summary> For the header of a <detail> element. The <summary> would show by default.
<time> For holding a machine-readable date and/or time while displaying a friendly date and/or time.
<video> For embedding video files.
<wbr> An opportunity to insert a line break within a word. (e.g., super<wbr>califragilistic<wbr>expialidocious)

Keep in mind that jQuery Mobile doesn't inherently make use of all - even most - of these new tags; in fact, one might argue that jQuery Mobile could be a little more semantic, making use of the <header> or <footer> tag, say, instead of lots of <div>s. Nonetheless, the jQuery Mobile is syntactically valid HTML5.

A First Example

Let's take a look at a quick first example - open up WhatIsjQueryMobile/Demos/html5/index.html in a browser and in your file editor to inspect the code. From a desktop browser you'll see something like this:

Basic HTML5 page

Code Sample:

WhatIsjQueryMobile/Demos/html5/index.html
<html>
<head>
   <title>A Simple Document</title>
</head>
<body>
  <header>
    <h1>Site Title</h1>
      <nav>
        <ul>
          <li><a href="#">link 1</a></li>
          <li><a href="#">link 2</a></li>
          <li><a href="#">link 3</a></li>
        </ul>
      </nav>
  </header>

  <section>
    <article>
      <h1>Page Title</h1>
      <h2>Subtitle</h2>
      <p>Content content content</p>
    </article>
  </section>
  <aside>
    <p>Sidebar info goes here</p>
  </aside>
  <footer>Footer content here</footer>
</body>
</html>

Presentationally, the page is less than stunning when viewed in a browser - we've not styled the elements at all - but the interesting bits are how we've marked up the content. Firstly, note that we've declared a doctype of html - this fact alone means this page is an HTML5 document.

Secondly, note that we have made use of the HTML5 semantic tags to imply meaning to the content we markup for viewing on the web:

  1. A header tag wraps the header of the page.
  2. The main navigation items are wrapped with a nav tag.
  3. An article tag wraps the main content, while an aside tag wraps the sidebar content.

HTML5 Forms

Our mobile sites will need to accept user input - registration forms, comment forms, and the like to ask users to send us, via form fields, some information. jQuery Mobile handles a good bit of this, but it's good to know about how HTML5 makes available a set of new form input types and attributes that enhance the user experience. Keep in mind that adoption for some of these new features is spotty at best; we'll cover the better implemented options.

There are 13 new input types:

  1. search
  2. tel
  3. url
  4. email
  5. datetime
  6. date
  7. month
  8. week
  9. time
  10. datetime-local
  11. number

We'll concentrate on a few of the more useful types for mobile.

Telephone

The tel type input expects a phone number. Many phones will present a numeric keyboard:

tel field

Dates

The date type of input allows the user to enter a date with no time zone. Some smartphone browsers present a date picker when a field of type date receives focus. iPhones with iOS version 5 or later, for instance, offer a date picker - earlier versions do not.

date field

Email

Fields of type email expect a valid email address. Many phones will show a contextually appropriate set of characters for input; the iPhone, for instance, displays the "@" character:

email field

Some browsers will validate the field as a valid email address.

Web Address

Fields of type url are for entering full website address. Many phones will show a contextually appropriate set of characters for input; the iPhone, for instance, displays the ".com" key:

url field

Some browsers will validate the field as a valid web address.

New Field Attributes

The placeholder attribute is among the more useful new HTML5 field attributes: it allows us to specify an example value for the field, a value which disappears when the user begins to enter content in the field.

The required attribute is very useful - but, sadly, not well-supported among mobile browsers: the automatic client-side HTML5 form validation that works on desktop browsers is lacking on their mobile counterparts.

HTML5 Form Example

Open WhatIsjQueryMobile/Demos/forms/index.html in a mobile browser - this is the page from which the screenshots on the previous section were taken.

Code Sample:

WhatIsjQueryMobile/Demos/forms/index.html
<form action="forms.html" method="post">
	<label for="name">Name</label>
	<input type="text" name="name" id="name" placeholder="Jane Doe">
    
	<label for="phone">Phone</label>
	<input type="tel" name="phone" id="phone">

	<label for="email">Email</label>
	<input type="email" name="email" id="email">

	<label for="website">Website URL</label>
	<input type="url" name="website" id="website">
	
    <label for="DOB">Date of Birth</label>
	<input type="date" name="DOB" id="DOB">

	<input type="submit">
</form>

We use a placeholder value for the first ("name") field, and ask the user for information of type tel, email, url, and date.

CSS3 Media Queries

Among the new features offered as part of CSS3, media queries are easily the most useful to us as designers and developers of mobile sites. A way to apply CSS rules selectively based on both the type of media and the physical properties of the device (browser, phone) being used to access the page, each media query comprises a media type (e.g. "screen") and zero or more logical expressions - a condition evaluating to true or false based on the conditions of particular media features. We can test our user's device for screen width, device width, orientation ("portrait" or "landscape"), and other features.

Media Query Features
Feature Possible Values Min/Max? Explanation
color int yes bits per color component
color-index int yes number of entries in color lookup table
device-aspect-ratio int/int yes aspect ratio
device-height length (pixels) yes height of the output device
device-width length (pixels) yes width of the output device
grid int no true for a grid-based device
height length (pixels) yes height of the rendering surface
monochrome int yes bits per pixel in a monochrome frame buffer
orientation "portrait" or "landscape" no orientation ("portrait" or "landscape") of the device
resolution "dpi" or "dpcm" yes resolution
scan "progressive" or "interlaced" no scanning process of "tv" media types
width length (pixels) yes width of the rendering surface

Let's look at a simple example of media queries. Open WhatIsjQueryMobile/Demos/mediaquery/index.html in a desktop browser; open up the same file and WhatIsjQueryMobile/Demos/mediaquery/style.css in a file editor to check out the code.

When the browser is wider than 768 pixels, the page renders with the two columns floated left and right. The red main column (an article inside of a section) occupies about two-thirds of the page, at left. The blue right sidebar column (an aside) sits to the right.

media query demo - wide browser

When we drag the browser to a width narrower than 768 pixels, the design changes:

  1. Both columns fill the width of the container element, instead of floating left and right;
  2. The main column's background changes to gray;
  3. The background of the sidebar column, now at bottom, changes to green.

Here's a screenshot of the narrow-browser rendering:

media query demo - narrow browser

Code Sample:

WhatIsjQueryMobile/Demos/mediaquery/index.html
<!doctype html>
<html>
<head>
  <title>Media Queries</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="container">
  <header>
    <h1>Site Title</h1>
    <nav>
      <ul>
        <li><a href="#">link 1</a></li>
        <li><a href="#">link 2</a></li>
        <li><a href="#">link 3</a></li>
      </ul>
    </nav>
  </header>
  <section>
    <article>
      <h1>Page Title</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
      quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
      consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
      cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
      proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
      <p>Content content content</p>
    </article>
  </section>
  <aside>
    <h2>Sidebar</h2>
    <p>Sidebar info goes here</p>
  </aside>
  <footer>Footer content here</footer>
</div>
</body>
</html>

Code Explanation:

The HTML page contains an article wrapped by a section; an aside wraps the sidebar content.

Code Sample:

WhatIsjQueryMobile/Demos/mediaquery/style.css
#container {
	width:80%;
	margin:0 auto;
}
section {
	float:left;
	width:55%;
	padding:2% 5%;
	background:#f00;
}
aside {
	float:right;
	width:25%;
	padding:2% 5%;
	background:#00f;
}

@media screen and (max-width: 768px) {
	section {
		float:none;
		width:90%;
		padding:5%;
		background:#ccc;
	}
	aside {
		float:none;
		width:90%;
		padding:5%;
		background:#0f0;
	}
}

footer {
	padding:5%;
	clear: both;
}

Code Explanation:

Unlike our earlier example, we employ a CSS stylesheet in this example. The media query dictates that "for viewing on a screen and at a maximum browser width of 768 pixels" the page should:

  1. Unfloat the section element;
  2. Set the width of the section element to 90%;
  3. Set the background color of the section to gray;
  4. Unfloat the aside element;
  5. Set the width of the aside element to 90%;
  6. Set the background color of the aside to green.