facebook google plus twitter
Webucator's Free jQuery Tutorial

Lesson: jQuery Mobile jQuery UI

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

jQuery's family of UI interface libraries - jQuery UI for desktops, and jQuery Mobile for smartphones and tablets - offer a set of interactions, widgets, events, and animations to solve common user-interface challenges. Both are well-documented, thoroughly tested, and easy to use.

Lesson Goals

  • Use jQuery UI and jQuery Mobile to extend the core jQuery library for desktop and mobile audiences.
  • Learn how jQuery UI interactions, widgets, and effects can be added to pages.
  • Use jQuery Mobile to easily create mobile-optimized web pages.

jQuery UI & jQuery Mobile

We often extend the core jQuery library with two user-interface libraries: jQuery UI, for desktops, and jQuery Mobile, for mobile devices.

We might use jQuery UI, a "curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library," to quickly and easily add autocomplete to an input search box, offer users drag-to-sort functionality in a list of items, or spice up a given page with animations and effects. jQuery Mobile, a "unified, HTML5-based user interface system for all popular mobile device platforms, built on the rock-solid jQuery" (and jQuery UI) libraries, provides a consistent, simple framework by which we can make our sites work well on phones and other mobile devices.

We will review both of the UI libraries below.

jQuery UI

jQuery UI, a JavaScript library built on top of jQuery and intended for desktop users, provides a set of interactions, effects, widgets, utilities, and themes for use on web pages. We'll take a quick look at each of these categories in turn.

To use jQuery UI, you must link to the library after first linking to the standard jQuery library. As with jQuery, you can link to the jQuery UI library either via a hosted CDN (from Google or jQuery) or by downloading and hosting the library yourself.

Note that jQuery UI is themeable: you can use the stock themes (a pre-designed set of CSS rules that govern how popup menus, buttons, and other elements look in response to user interactions) or build your own themes with jQuery UI's ThemeRoller.

jQuery UI's ThemeRoller gives you a visual tool to set styles for just about any aspect of jQuery UI-produced elements, from header color to rounded-corner radius size to drop shadowing. To use it, visit jqueryui.com/themeroller:

ThemeRoller

Set desired options from the panels at left; you will see the sample content change to reflect your settings. Once you are finished, click the "Download theme" button at upper left, choose the jQuery UI version and modules from the options presented on the next screen, and save the zipped download to your computer. The zipped archive will contain both JavaScript files (jQuery and jQuery UI) and CSS files (reflecting your ThemeRoller style settings), in plain and minified versions.

Interactions

jQuery UI offers the following interactions, which are ways to add mouse-based behaviors to elements:

jQuery UI Interactions
Behavior Explanation Code
Draggable Enable draggable functionality on any element $("#draggable").draggable();
Droppable Create a target for a droppable element $('#droppable').droppable({ drop: function(event, ui) { $(this) .addClass('dropped') .find('h2') .html('Dropped'); } });
Resizable Change the size of an element with the mouse $('#resizable').resizable();
Selectable Select one or more elements with the mouse $('#selectable').selectable();
Sortable Reorder elements with the mouse $('#sortable').sortable();

We will use an example to review each of the interactions. Open the file jqy-mobile-ui/Demos/jquery-ui-interactions.html in a browser and in an editor to view the code. The page displays five areas to illustrate each interaction:

jQuery UI Interactions

Code Sample:

jqy-mobile-ui/Demos/jquery-ui-interactions.html
---- C O D E   O M I T T E D ----

	<script>
		$(document).ready(function() {
			$('#draggable').draggable();
			$('#droppable').droppable({
				drop: function(event, ui) {
					$(this)
					.addClass('dropped')
					.find('h2')
					.html('Dropped');
				}
			});
			$('#resizable').resizable();
			$('#selectable').selectable();
			$('#sortable').sortable();
		});
	</script>
	<style>
		.container {
			width:30%;
			margin:0 1% 1% 0;
			float:left;
			height:200px;
			background-color:#fbb;
			padding:1%;
		}
		.widecontainer {
			width:98%;
			margin-bottom:1%;
			clear:left;
			background-color:#fbb;
			height:100px;
		}
		.contained {
			width:90px;
			height:90px;
			padding:10px;
			background-color:#c00;
		}
		h3 {
			float:right;
			font-size:14px;
			font-weight:bold;
			color:#444;
			margin:5px 5px 0 0;
		}
		.dropped {
			background-color:#fff;
		}
		ul {
			list-style:none;
			margin:0;
			padding:0;
		}
		ul li {
			float:left;
			margin:20px 10px 0 10px;
			padding:5px 15px;
			background-color:#c00;
		}
		#selectable .ui-selecting {
			background-color: #600;
		}
		#selectable .ui-selected {
			background-color: #000;
			color: white;
		}
	</style>
</head>
<body>
<div id="draggablecontainer" class="container">
	<h3>Draggable</h3>
	<div id="draggable" class="contained">Drag Me</div>
</div>
<div id="droppable" class="container">
	<h3>Droppable</h3>
	<h2>Drop Here</h2>
</div>
<div id="resizablecontainer" class="container">
	<h3>Resizable</h3>
	<div id="resizable" class="contained">Resize Me</div>
</div>
<div id="selectablecontainer" class="widecontainer">
	<h3>Selectable</h3>
	<ul id="selectable">
		<li>One</li>
		<li>Two</li>
		<li>Three</li>
		<li>Four</li>
		<li>Five</li>
		<li>Six</li>
		<li>Seven</li>
		<li>Eight</li>
		<li>Nine</li>
		<li>Ten</li>
	</ul>
</div>
<div id="sortablecontainer" class="widecontainer">
	<h3>Sortable</h3>
	<ul id="sortable">
		<li>One</li>
		<li>Two</li>
		<li>Three</li>
		<li>Four</li>
		<li>Five</li>
		<li>Six</li>
		<li>Seven</li>
		<li>Eight</li>
		<li>Nine</li>
		<li>Ten</li>
	</ul>
</div>
</body>
</html>

The upper-left and upper-right of the page shows two red divs ("Drag Me" and "Resize Me"); each is about 100px on a side. The user can drag the upper-left square with the mouse to any position on the page - the code $('#draggable').draggable() enables this functionality.

Dropping the left square into the "Drop Here" area changes the color and title of the 'dropzone'; this is the code starting with $('#droppable').droppable, where we add a class to the div and change the html of the h2.

We set the upper-right div to be resizable with $('#resizable').resizable(). Note the pull bars on the lower right corner of the element; these derive from the jQuery UI CSS file, jqy-libs/ui-lightness/jquery-ui-1.10.3.custom.min.css

We set the unordered list in the next-to-last, full-width div to be selectable with $('#selectable').selectable(): the user can select one or more elements with the mouse by pressing and holding on the Command key (for Macs) or Control (for Windows).

Lastly, we enable sortable functionality on the bottom set of elements (also an unordered list) with $('#sortable').sortable(); the user can drag elements with the mouse to sort them.

Widgets

jQuery UI offers a set of powerful widgets that enable complex functionality with minimal coding, and allow precise customization with more work. All of the widgets are amenable to jQuery UI's theming, displaying according to one of the stock themes or your custom theme, as you decide.

jQuery UI Widgets
Widget Explanation Code
Accordion Collapsible content panels for displaying information in small space $('#acc').accordion()
Autocomplete Select from a pre-populated list of values as user types in field $('#tags').autocomplete({ source: aTags })
Button Enhance standard form elements as themeable buttons with hover and active styles $('a').button()
Datepicker Select a date from a popup calendar $('#dp').datepicker()
Dialog Open content in an interactive overlay $('#dlg').dialog()
Menu Themeable menu with mouse and keyboard interactions $('#mnu').menu()
Progressbar Display status of a determinate or indeterminate process $('#pgbar').progressbar({ value: 41 })
Slider Drag handle to select numeric value $('#slide').slider()
Spinner Enhance a text input for entering numeric values, with up/down buttons and arrow-key handling $('#sp').spinner()
Tabs Tabbed content area with multiple panels, each associated with a header in a list $('#tbs').tabs()
Tooltip Customizable, themeable tooltips to replace native tooltips $(document).tooltip()

From accordion panels for displaying large volumes of content more efficiently to themeable buttons to sliders and spinners to tabs and tooltips, jQuery UI offers a wide range of useful widgets. Check out the jQuery UI website for full details; we will review a few of the more common (and more useful) widgets via an example.

Open the file jqy-mobile-ui/Demos/jquery-ui-widgets.html in a browser and in a code editor to view the source. This demo shows an accordion on the left: users can click a title to toggle desired content open, closing the other panes. The middle of the demo shows an example of autocomplete: try typing a number ("one", "two", "three", "four", or "five") to watch the suggestions change to match your input. The right of the demo displays a datepicker, allowing users to click from a popup month calendar to choose a date.

jQuery UI Widgets

Code Sample:

jqy-mobile-ui/Demos/jquery-ui-widgets.html
---- C O D E   O M I T T E D ----

		$(document).ready(function() {
			$('#acc').accordion();
			 var mylist = [
					"one",
					"two",
					"three",
					"four",
					"five"
				];
				$('#search').autocomplete({
					source: mylist
				});
				$('#dp').datepicker();
		});
	</script>
	<style>
		#acc {
			width:32%;
			margin-right:1%;
			float:left;
		}
		#autocompletecontainer {
			width:32%;
			margin-right:1%;
			float:left;
		}
		#datepickercontainer {
			width:32%;
			float:left;
		}
	</style>
</head>
<body>
<div id="acc">
	<h3>Item 1</h3>
	<div>
		<p>content 1 content 1 content 1</p>
	</div>
	<h3>Item 2</h3>
	<div>
		<p>content 2 content 2 content 2</p>
	</div>
	<h3>Item 3</h3>
	<div>
		<p>content 3 content 3 content 3</p>
	</div>
</div>
<div id="autocompletecontainer">
	<label for="search">Start typing (try "o" or "t"):</label> <input type="text" name="search" id="search">
</div>
<div id="datepickercontainer">
	<label for="dp">Select date:</label> <input type="text" name="dp" id="dp">
</div>
</body>
</html>

jQuery UI accordions are marked up as a container div, with the id of the container element referenced in the call to accordion() - in our case, $('#acc').accordion(). h3's form the clickable titles. The div following the h3 contain the content that is toggled open/closed; this div can contain any valid HTML.

At its most basic, jQuery UI's autocomplete connects a JavaScript array to an input element and offers suggestion as the user types; in our case, the array myList (["one", "two", "three", "four", "five"]) serves as the list of suggestions connected to the field with id #acc.

We often use autocomplete in much more complex ways, drawing the list of suggestions from a same-site or external JSON feed via Ajax, hand-tooling the format or display of data, performing actions when the user selects an item, etc. See the jQuery UI website for a good list of examples and API details.

jQuery UI's datepicker widget is a convenient tool for adding a popup calendar. In our example, $('#dp').datepicker() adds the functionality to the input of id #dp. The widget offers a range of customizations; see the jQuery UI website for details on how to format and control the display of dates, handle events, localize the calendar, and other options.

More on Autocomplete

Autocomplete is such a useful tool that it deserves a bit more discussion. The autocomplete widget can derive the set of suggestions from a simple JavaScript array, a JavaScript array of hashes (objects), or an external JSON datasource. Additionally, we have complete control over the interaction, sending the user to a new page (for example) when a suggested item is selected from the drop-down list. Consider the following example:

var items = [
	{
		label: "jquery",
		url: "jquery.php"
	},
	{
		label: "jquery-ui",
		url: "jquery-ui.php"
	},
	{
		label: "sizzlejs",
		url: "sizzle.php"
	}
];
$('#search').autocomplete({
	source: items,
	select: function( event, ui ) {
		window.location.href = ui.item.url;
	}
});

We create a three-element array (items) of hashes and use it as the source for our autocomplete. Autocomplete's select event allows us to specify what happens when the user selects one of the suggested values; in this case, we redirect them to a new page, drawing the value from the url field of the chosen item.

Effects

jQuery UI effects mimic core jQuery effects, with the addition of animations and control over duration, easing, and other properties. As the docs state: "[e]ffects add support for animating colors and class transitions, as well as providing several additional easings [with] a full suite of custom effects... for use when showing and hiding elements or just to add some visual appeal."

Where the jQuery core addClass method, for example, adds a class to any element(s) matching the found set, the jQuery UI addClass method does the same (i.e. adds a class to the matched elements) but also animates the changes of background color, width, height, etc., over the specified duration. (Note that some properties cannot be animated: background images, for example, are changed at the end of the duration.) Note that jQuery UI animations differ from CSS3 transitions; jQuery UI animations are often used as fallbacks for older browsers that do not support CSS3 transitions.

jQuery UI effects include the following:

  • Add Class
  • Color Animation
  • Effect
  • Hide
  • Remove Class
  • Show
  • Switch Class
  • Toggle
  • Toggle Class

We will illustrate common properties of effects through the demo below, in which we toggle a div with various effects; see the jQuery UI website for full API details on effects methods.

Open the file jqy-mobile-ui/Demos/jquery-ui-effects.html in a browser and in a code editor to view the source. The page displays a div in the upper left with a red border, light-grey background, and some sample text; the controls on the right allow the user to toggle (to display or hide) the element and to choose the effect ("Blind", "Bounce", etc.) and duration of animation:

jQuery UI Effects

Code Sample:

jqy-mobile-ui/Demos/jquery-ui-effects.html
---- C O D E   O M I T T E D ----

	<script>
		$(document).ready(function() {
			$('#go').click(function() {
				var chosen_effect = $('#effect').val();
				var chosen_duration = $('#duration').val();
				if (chosen_effect != '' && chosen_duration != '') {
					$('#item').toggle(chosen_effect, parseInt(chosen_duration));
				}
			})
		});
	</script>
	<style>
		#itemcontainer {
			width:300px;
			height:300px;
			float:left;
		}
		#item {
			width:200px;
			margin:20px 0 0 20px;
			padding:20px;
			border:4px solid red;
			background:#dedede;
			border-radius: 10px;
		}
		#item h2 {
			margin:0;
			padding:0;
			background:#000;
			padding:3px 7px 3px 7px;
			color:#fff;
		}
		#controls {
			padding:20px;
		}
	</style>
</head>
<body>
<div id="itemcontainer">
	<div id="item">
		<h2>Item 1</h2>
		<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
	</div>
</div>
<div id="controls">
	<h2>Toggle</h2>
	Effect:
	<select id="effect">
		<option value="">-select-</option>
		<option value="blind">Blind</option>
		<option value="bounce">Bounce</option>
	    <option value="clip">Clip</option>
	    <option value="drop">Drop</option>
	    <option value="explode">Explode</option>
	    <option value="fold">Fold</option>
	    <option value="highlight">Highlight</option>
	    <option value="puff">Puff</option>
	    <option value="pulsate">Pulsate</option>
	    <option value="scale">Scale</option>
	    <option value="shake">Shake</option>
	    <option value="size">Size</option>
	    <option value="slide">Slide</option>
	</select>
	Duration:
	<select id="duration">
		<option value="">-select-</option>
		<option value="100">100</option>
		<option value="200">200</option>
		<option value="400">400 (default)</option>
		<option value="1000">1000</option>
		<option value="2000">2000</option>
	</select>
	<input type="button" id="go" value="Go">
</div>
</body>
</html>

The #item element sits upper left on the page with an h2 title and some greeking for content. We add a click handler for the button on the right: if the user has selected both an effect and a duration, then we toggle div#item with the selected parameters. Note that the click handler ensures that both an effect and duration have been selected, and only performs the toggle if both options are set.

jQuery UI's allows us to animate color changes, gradually changing from one color to another over a set duration. We might, for instance, change the background and foreground colors of a div as the user mouses in and out:

<div id="a">sample content</div>

...

<script>
$('div#a').hover(
	function() {
		$(this).animate({
			backgroundColor: "#000",
			color: "#fff"
		});
	},
	function() {
		$(this).animate({
			backgroundColor: "#fff",
			color: "#000"
		});
	}
)
</script>

As the user mouses into the div, the background color would change (animate) to black with white text; the reverse would occur as the user mouses out of the div.

Next we'll ask you to try out these concepts with an exercise.

jQuery UI Autocomplete

Duration: 20 to 30 minutes.

In this exercise, you will add autocomplete functionality to a page to allow users to quickly search for and jump to content farther down on the page.

  1. Open jqy-mobile-ui/Exercises/jqueryui/index.html and jqy-mobile-ui/Exercises/jqueryui/js/load.js in a code editor.
  2. Note that, in index.html, each of the h2s has an appropriate id, so that we can use an anchor in the page address to jump to a desired section: index.html#fruit, index.html#blogtitle, etc. Note that you need make no changes to index.html.
  3. Add code to load.js:
    • Write jQuery code to iterate over all h2s on the page to add a hash (each with a value for keys label and url) to the array for each h2
    • Add autocomplete to the #q field so that when the user starts typing, a suggested list of options ('Fruit', 'Vegetables', 'Blog', etc.) appears.
    • Use autocomplete's select event handler to redirect the user to the appropriate anchor (index.html#fruit, index.html#vegetables, index.html#blogtitle, etc.) when an item is selected from the autocomplete list.
    • Test your work in a browser
  4. Use jQuery UI to animate the background and foreground color table rows in the table (at the bottom of the page) with id #fruits.

Solution:

jqy-mobile-ui/Solutions/jqueryui/js/load.js
$(document).ready(function() {
    //create empty "titles" array
	var titles = [];

    //iterate over all h2s on the page;
    //for each h2, add a hash to the "titles" array,
    //with fields for title (the h2's html) and
    //url (the h2's id)
    $('h2').each(function() {
        titles.push({
        	label: $(this).html(),
        	url: $(this).attr('id')
        })
    });

    //use the "titles" array as the datasource for
    //autocomplete for the #q input field; when the user
    //selects a suggested option, redirect them to the
    //appropriate anchor, jumping down the page to the
    //correct id
    $('#q').autocomplete({
		source: titles,
        select: function( event, ui ) {
          window.location.href = '#'+ui.item.url;
        }
	});

    //animate table row background/foreground color
    //as the user hovers over each row; the first
    //function is the mouse-in event and the second
    //is the mouse-out event
    $('table#fruits tr').hover(
        function() {
            $(this).animate({
                backgroundColor: "#600",
                color: "#fff"
            });
        },
        function() {
            $(this).animate({
                backgroundColor: "#fff",
                color: "#000"
            });
        }
    )
});

If the user were to type "bl" into the "On this page" field, then "Vegetables" and "Blog" should (since both contain the string "bl") appear as options:

jQuery UI autocomplete exercise

We iterate ($('h2').each) over all h2s on the page and, for each one, push a new hash onto the titles array, with fields populated from the text (.html()) and id attribute (.attr('id')) of the respective h2.

With the titles array now populated appropriately, we use it as the source for the jQuery UI autocomplete on the #q input field. We specify the action resulting from the user selecting any of the suggested items with the select event handler, redirecting the user to the appropriate anchor (window.location.href = '#'+ui.item.url).

We use animate to change the background and text color of each row in the #fruits table, changing to a dark red background with white text when moused over, and back to white background with black text when moused out.

jQuery Mobile

jQuery Mobile is the jQuery UI equivalent for mobile devices like smartphones, tablets, e-readers, and the like. More so than jQuery UI, jQuery Mobile expects that the page's markup - your HTML code - to which it is applied conform to its conventions. You can set configuration options to get around this, but it is usually easier to markup a "page", for example, as a div with attribute data-role="page". As you'll see, getting jQuery Mobile to work effectively mostly means marking up your pages with the appropriate DOM elements with the appropriate attributes.

Here are some of the more common data- attributes used by jQuery Mobile:

jQuery Mobile Data Attributes
Attribute Explanation
data-theme Values are swatch letter (a - z)
data-role Tells jQuery Mobile what type of element this is; values include content, header, footer, button, collapsible, etc.
data-mini A value of true specifies that this element should be displayed in compact-sized version
data-icon Specify which of jQuery Mobile's pre-built icons to be used, or reference custom icon
data-iconpos Values left, right, top, bottom determine placement of icon for elements like buttons, collapsibles, navbar, etc.

To use jQuery Mobile, first include the jQuery library (either from code hosted on your own site or via a CDN) and then include the jQuery Mobile JavaScript file.

jQuery Mobile is themed. You will want to either include the default jQuery Mobile CSS file or, if you create a custom theme, include a custom-theme CSS file. You can create custom themes by using jQuery Mobile's ThemeRoller, a what-you-see-is-what-you-get visual designing tool, or by hand crafting CSS yourself.

Covering all of jQuery Mobile in detail is outside the scope of this course; we will introduce the basics through an demo example. Open up jqy-mobile-ui/Demos/jquery-mobile-pages.html in a browser, preferably from a mobile device (though it will work from a desktop browser), and in a code editor to view the source. On first load, the page looks like this:

jQuery Mobile pages

Code Sample:

jqy-mobile-ui/Demos/jquery-mobile-pages.html
<!DOCTYPE html> 
<html>
<head>
	<title>jQuery Mobile Pages</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />

	<!-- link to jQuery and jQuery Mobile JavaScript libraries: -->
	<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
	<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
</head>

<body>

<!-- the div below is a page - the home page -->
<div data-role="page" id="home">

	<!-- the div below is the home page's header -->
	<div data-role="header">
		<h1>Home</h1>
		<div data-role="navbar">
	        <ul>
	            <li><a href="#home" class="ui-btn-active ui-state-persist" data-icon="home">Home</a></li>
	            <li><a href="#about" data-icon="star">About</a></li>
	            <li><a href="#contact" data-icon="info">Contact</a></li>
	        </ul>
	    </div>
	</div>

	<!-- the div below is the home page's main content -->
	<div data-role="content">
		<p>homepage content homepage content</p>
		<p>homepage content homepage content</p>
	</div>

	<!-- the div below is the home page's footer -->
	<div data-role="footer">
		<h4>123 Fake St. Anywhere USA</h4>
	</div>
</div>

<!-- the div below is a page - the about page -->
<div data-role="page" id="about">
	<div data-role="header">
		<h1>About</h1>
		<div data-role="navbar">
	        <ul>
	            <li><a href="#home" data-icon="home">Home</a></li>
	            <li><a href="#about" class="ui-btn-active ui-state-persist" data-icon="star">About</a></li>
	            <li><a href="#contact" data-icon="info">Contact</a></li>
	        </ul>
	    </div>
	</div>
	<div data-role="content">
		<p>about content about content</p>
		<p>about content about content</p>
	</div>
	<div data-role="footer" data-theme="e">
		<h4>123 Fake St. Anywhere USA</h4>
	</div>
</div>

<!-- the div below is a page - the contact page -->
<div data-role="page" id="contact">
	<div data-role="header">
		<h1>Contact</h1>
		<div data-role="navbar">
	        <ul>
	            <li><a href="#home" data-icon="home">Home</a></li>
	            <li><a href="#about" data-icon="star">About</a></li>
	            <li><a href="#contact" class="ui-btn-active ui-state-persist" data-icon="info">Contact</a></li>
	        </ul>
	    </div>
	</div>
	<div data-role="content">
		<p>contact content contact content</p>
		<p>contact content contact content</p>
	</div>
	<div data-role="footer">
		<h4>123 Fake St. Anywhere USA</h4>
	</div>
</div>
<script>
	//handle for orientation-change event:
	$(window).on('orientationchange', function(event) {
		alert(event.orientation);
	});
</script>
</body>
</html>

First off, notice that the page is marked up as valid HTML5; jQuery mobile makes extensive use of HTML5 data- attributes to render various elements. We use the viewport meta tag to scale the width of the page to the width of the user's device's viewing pane. We include (from the code.jquery.com CDN) jQuery Mobile's CSS file, the jQuery library, and the jQuery Mobile library. You must include jQuery before jQuery Mobile.

The basic unit of jQuery Mobile sites are "pages" - but notice that our one html file includes three pages, each denoted by <div data-role="page">. With jQuery Mobile sites, pages can all live in one physical file or in multiple files; regardless, only one page will show in the user's browser at a time. We give each page (each <div data-role="page">) a unique id and use that <div data-role="page"> to link between pages.

Typically, you will divide each page into a header, content area, and footer: each is a div with the appropriate value for the data-role attribute. Here, we use an h1 tag in the header to show each page's title and add some sample content to each page's content area and footer.

One of the great features of jQuery Mobile is the set of widgets and UI elements that you can use on your page. Each form element, collapsible content widget, navbar, dialog, or other element is optimized for mobile viewing - tested across many different devices and designed for conserving valuable screen real estate on small screens. Here is a summary of the more common elements; note the extensive use of data- attributes:

Button

Create a button, usually from a link:

<a href="#home" data-role="button">Home</a>

Collapsible

Create a collapsible block of content: any (H1-H6) header element serves as the displayed title of the collapsible which, when clicked, toggles the initially-hidden content:

<div data-role="collapsible">
<h3>Header Title</h3>
	<p>The collapsible's content</p>
</div>

Dialog

Link to another page as a modal dialog by adding data-rel="dialog":

<a href="#about" data-rel="dialog">Open Dialog</a>

Navbar

Display up to five navigation buttons, with optional icons:

<div data-role="navbar">
	<ul>
		<li><a href="#home">Home</a></li>
		<li><a href="#about">About</a></li>
	</ul>

Slider

Display horizontal control to allow users to select from set range of numeric values:

<input type="range" name="sl" id="sl" value="40" min="0" max="100">

Visit the jQuery Mobile website for a full list of examples and code.

In our example, we use a navbar on each page - a div with attribute data-role="navbar". Note that each contains an unordered list, that we mark which element should be "active" (i.e. representing the current page) with class="ui-btn-active ui-state-persist", and that we set an icon for each with the data-icon attribute. See the jQuery Mobile website for a list of built-in icons; you can also design your own.

As mentioned above, jQuery Mobile ships with an extensive theming framework. You can apply any of the six stock themes (deriving from the CSS file we included) by adding the attribute, for example, data-theme="e" to an element. We have done this for the footer on the "about" page (note that it shows in yellow). Letters "a" through "e" represent the stock themes.

Since jQuery Mobile is built on jQuery, we can apply custom jQuery code to our mobile pages just as we might to our desktop pages. jQuery Mobile extends jQuery to the mobile environment; perhaps most interestingly, we can handle orientation-change events (when the user tilts the phone from portrait to landscape orientation) with the orientationchange event handler. In our example, we popup a JavaScript alert when the device changes orientation with code at the very bottom of the file:

jQuery Mobile orientation change

The jQuery Mobile website has a well-written set of examples, sample code, and API docs - we encourage you to visit to learn more. The exercise below will ask you to test out some of the concepts we covered above, but feel free to add other elements of jQuery Mobile.

jQuery Mobile

Duration: 25 to 35 minutes.

Build a two-page jQuery Mobile site. If possible, try testing the site from a mobile device or emulator.

  1. Open jqy-mobile-ui/Exercises/jquerymobile/index.html in a code editor.
  2. The needed CSS and JavaScript files been included for you.
  3. Add a page (a div with attribute data-role="page") for "Home" and a page for "Contact".
  4. For each page, add an appropriate header, content area, and footer, with some sample content.
  5. Add a navbar for each header, with appropriate links to each of the two pages; add classes to ensure the appropriate nav item shows as active on each page.
  6. Add a paragraph of class orientation at the bottom of each page's content area.
  7. At the bottom of the page, add an event handler: set the text of each .orientation paragraph to the appropriate value ("portrait" or "landscape"); note that the orientationchange event is called on page load, to set the text when the page first loads.
  8. The site should look like this (for the "Contact" page): jQuery Mobile exerise
  9. Optionally, visit the jQuery Mobile website to find other UI elements or events to test out.

Solution:

jqy-mobile-ui/Solutions/jquerymobile/index.html
<!DOCTYPE html> 
<html>
<head>
	<title>jQuery Mobile</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
	<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
	<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
</head>

<body>

<!-- the home page: -->
<div data-role="page" id="home">

	<!-- home page header: -->
	<div data-role="header">
		<h1>Home</h1>
		<div data-role="navbar">
	        <ul>
	        	<!-- classes "ui-btn-active" and "ui-state-persist" -->
	        	<!-- make "Home" link active: -->
	            <li><a href="#home" class="ui-btn-active ui-state-persist" data-icon="home">Home</a></li>
	            <li><a href="#contact" data-icon="grid">Contact</a></li>
	        </ul>
	    </div>
	</div>

	<!-- home page content: -->
	<div data-role="content">
		<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat.</p>
		<p class="orientation"></p>
	</div>

	<!-- home page footer: -->
	<div data-role="footer">
		<h4><a href="mailto:info@example.com">info@example.com</a></h4>
	</div>
</div>

<!-- the contact page: -->
<div data-role="page" id="contact">

	<!-- contact page header: -->
	<div data-role="header">
		<h1>Contact</h1>
		<div data-role="navbar">
	        <ul>
	        	<!-- classes "ui-btn-active" and "ui-state-persist" -->
	        	<!-- make "Contact" link active: -->
	            <li><a href="#home" data-icon="home">Home</a></li>
	            <li><a href="#contact" class="ui-btn-active ui-state-persist" data-icon="grid">Contact</a></li>
	        </ul>
	    </div>
	</div>

	<!-- contact page content: -->
	<div data-role="content">
		<p>Cui tristique usitas. Bis ex populus typicus saepius populus olim exputo inhibeo fere haero. Sino transverbero olim abluo et mos nunc et nullus. Bis laoreet macto at ullamcorper eum.</p>
		<p class="orientation"></p>
	</div>

	<!-- contact page footer: -->
	<div data-role="footer">
		<h4><a href="mailto:info@example.com">info@example.com</a></h4>
	</div>
</div>
<script>
	//handler for orientation-change event:
	$(window).on('orientationchange', function(event) {
		//on orientation change, set content of div with appropriate text:
		$('.orientation').html('You are in <em>' + event.orientation + '</em> mode.');
	});
	//call event handler when page first loads, to set orientation message:
	$(window).orientationchange();
</script>
</body>
</html>

We mark up each page with <div data-role="page">; each page contains a div to represent the header, content area, and footer, with data-role attribute values of data-role, content, and footer, respectively. Each page div gets a unique id.

The navbar element goes in each header. Links point to the id of each page. We use classes ui-btn-active and ui-state-persist to ensure the correct links show as active for their respective pages.

An event handler at the bottom of the pages uses jQuery's html() method to set the inner text of all paragraphs of class orientation whenever the user changes the devices orientation.