The jQuery Mobile API provides an extra level of control over the customization of your mobile website. Everything from the custom setup of global options to hooking into interaction events and working with exposed methods is possible with the API and is covered in this article. By the end of this article, you will know how to granularly define the custom options you want to use in your mobile website as well as how to write custom code that interacts with the jQuery Mobile framework.
This article covers a selection of useful properties, events, and exposed methods from the jQuery Mobile framework. Each section explains the options and provides a code sample to show how it's done. To run any of the code samples, you must first download the latest version of jQuery and the jQuery Mobile framework or reference the files directly from the jQuery content delivery network (CDN) within your HTML file (see Resources).
The following global options are available through the jQuery Mobile API and allow you to change the way jQuery Mobile behaves by default:
- Extending jQuery Mobile's initialization event
- Creating custom namespaces
- Page initialization
- Customizing the subpage URL key
- Setting active page and button classes
- Setting the default page and dialog transitions
- Customizing loading and error messages
Extending jQuery Mobile's initialization event
jQuery Mobile includes an initialization event that loads before jQuery's
document.ready event even loads. jQuery Mobile
actually triggers its initialization event, called
mobileinit, on the document object itself. This
allows you to override and extend jQuery Mobile's default global options,
which is the starting point for this entire article. To extend the
mobileinit event, you need to add your custom
JavaScript event handler before jQuery Mobile is loaded and after the
jQuery framework has loaded (see Listing 1).
Listing 1. Extending the jQuery Mobile
mobileinit event<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="custom-jqm-mobileinit.js"></script> <script type="text/javascript" src="jquery.mobile.js"></script> |
To extend the mobileinit event, you first need
to bind to it with a custom function. Listing 2 shows an example that uses
the bind method to extend the
mobileinit event.
Listing 2. Binding to the
mobileinit event
$(document).bind("mobileinit", function() {
// Override global options here
});
|
When you are successfully binding to the mobileinit event, you can override
the global options. To override the global options, you can either use
jQuery's extend method to extend the
$.mobile object (see Listing 3) or simply override
individual properties by setting them directly.
Listing 3. Extending the
$.mobile object
$(document).bind("mobileinit", function() {
$.extend( $.mobile , {
property = value
});
});
|
If there are multiple properties that you want to update, the
extend method is a cleaner option because you
don't need to write the $.mobile object
multiple times. However, if you only have one property that you want to
update, it takes less lines of code to simply set the property
individually (see Listing 4).
Listing 4. Overriding individual property values
$(document).bind("mobileinit", function() {
$.mobile.property = value;
});
|
The $.mobile object is the starting point for
setting all properties.
You can customize the HTML5 data- attributes,
such as data-role, through namespaces. A
namespace allows you to add a custom name that will appear between the
data- and -role
portion of the data-role attribute, for
example. The $.mobile property that allows you
to customize the namespace is ns. Listing 5
shows an example of setting a custom namespace using the
ns property.
Listing 5. Create a custom namespace
$(document).bind("mobileinit", function() {
$.mobile.ns = "my-custom-ns";
});
|
The custom namespace used in Listing 5 produces
data-my-custom-ns-role rather than
data-role, which allows you to target these
namespaces via CSS selectors. Targeting the custom namespaces via CSS
selectors allows an additional way to design a custom theme for mobile
widgets that use those namespaces.
jQuery Mobile includes a property named
autoInitializePage that determines whether the
web page should be initialized. By default the value of this property is
set to true, therefore the page is always initialized when the document is
ready. However, by extending the $.mobile
object you can set this property to false and handle page initialization
at a later time. Listing 6 shows an example of how you can temporarily
delay the page initialization while other scripts run. If you have a large
amount of client-side JavaScript running on the web page, it might be a
good idea to delay initialization until the DOM completes loading and the
client-side JavaScript has a chance to run.
Listing 6. Setting the auto initialization for mobile web pages
<!DOCTYPE HTML>
<html>
<head>
<title>Understanding the jQuery Mobile API</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).bind("mobileinit", function() {
$.mobile.autoInitializePage = false;
});
</script>
<script type="text/javascript" src="jquery.mobile.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="content">
<ul data-role="listview" id="my-list"></ul>
</div>
</div>
<script type="text/javascript">
$('#my-list').html('<li><a href="page-2.html">Link to another page</a></li>');
$.mobile.autoInitializePage = true;
</script>
</body>
</html>
|
Customizing the subpage URL key
When referencing subpages, jQuery Mobile uses a URL parameter key of
ui-page by default. You can change this key
through a property of the $.mobile object named
subPageUrlKey. Any string value that this
property is updated to reflects in widget-generated subpage URLs. For
example, if you use a custom subPageUrlKey of
my-page, the default URL of
web-page.html&ui-page=value becomes
web-page.html&my-page=value.
In addition to providing a way to create more attractive URLs, custom subpage URL keys can also provide a way to shorten URLs or set their values to something more specific to the website that is using them.
Setting active page and button classes
When a web page includes the jQuery Mobile framework, there is a default
CSS class that is automatically applied to the
ui-page element. To change the default value,
which is ui-page-active, you simply change the
activePageClass property of the
$.mobile object. By updating this class, the
default CSS included with the framework no longer applies its styling to
the ui-page-active class because it no longer
exists. Therefore, it is important to create your own custom CSS class
that corresponds to the value you provide for this property.
Setting the default page and dialog transitions
By default, pages and dialogs include a transition effect in jQuery Mobile
when page changes are handled via Ajax. The default page transition is
slide, while the default dialog transition is
pop. To change these values, you need to target
the defaultPageTransition or
defaultDialogTransition property. Listing 7
shows how easy it is to change the values of these properties.
Listing 7. Setting the default page and dialog transitions
$(document).bind("mobileinit", function() {
$.mobile.defaultPageTransition = "fade";
$.mobile.defaultDialogTransition = "fade";
});
|
In this example, the transition for both pages and dialogs is a fading
effect. The framework includes six CSS-based transition effects:
slide, slideup,
slidedown, pop,
fade, and flip. You
can also apply these effects directly on hyperlinks by including the
data-transition attribute.
Customizing loading and error messages
Two other global options that the framework offers control over are the
loading and error messages. The loading message shows a string value of
loading by default. To update this property,
you simply need to target the loadingMessage
property. In Listing 8, I change the default loading message from
loading to
Please wait. As a result, when Ajax is used to
load pages, a small dialog appears with my custom loading message.
Listing 8. Setting the default loading message
$(document).bind("mobileinit", function() {
$.mobile.loadingMessage = "Please wait";
});
|
The default value of the pageLoadErrorMessage is
Error Loading Page. I update this message to
change it to something more user-friendly in Listing 9.
Listing 9. Setting the default error message
$(document).bind("mobileinit", function() {
$.mobile.pageLoadErrorMessage = 'Sorry, something went wrong. Please try again.';
});
|
Hooking into jQuery Mobile events
You can extend the following event types using the jQuery Mobile API:
- Touch events
- Orientation events
- Scroll events
There are a number of touch events that are customizable in jQuery Mobile.
However, these events are
available only when the user who is interacting with a touch-enabled device
accesses your jQuery Mobile website. When these events are available, you
can trigger any custom JavaScript as a response to five different events:
tap, taphold,
swipe, swipeleft,
and swiperight. Each of these is
self-explanatory, as you can see in Table 1.
Table 1. Customizable touch events for jQuery Mobile
| Event | Description |
|---|---|
tap | Triggers when someone quickly taps the screen. |
taphold | Triggers when someone taps the screen and continues to touch the screen for about one second. |
swipe | Triggers when the web page is dragged horizontally or vertically.
This event is actually the only event that has associated
properties. These properties are
scrollSupressionThreshold,
durationThreshold,
horizontalDistanceThreshold, and
verticalDistanceThreshold. |
swipeleft | Triggers when the web page is dragged to the left. |
swiperight | Triggers when the web page is dragged to the right. |
To bind to any of these touch events, you need to use the
document.ready event. When the document is
ready, you can access an element and bind your selected touch event
(see Listing 10).
Listing 10. Binding to touch events
<!DOCTYPE HTML>
<html>
<head>
<title>Understanding the jQuery Mobile API</title>
<link rel="stylesheet" href="jquery.mobile.css" />
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".tap-hold-test").bind("taphold", function(event) {
$(this).html("Tapped and held");
});
});
</script>
<script src="jquery.mobile.js"></script>
</head>
<body>
<div data-role="page" id="my-page">
<div data-role="header">
<h1>Header</h1>
</div>
<div data-role="content">
<ul data-role="listview" id="my-list">
<li class="tap-hold-test">Tap and hold test</li>
</ul>
</div>
</div>
</body>
</html>
|
As you can see, the code binds a taphold touch
event to a list item. When the document is ready, the list item in this
example is available to be targeted via jQuery. So, it is targeted and
bound to the taphold event, which changes the
HTML within the list item.
On smartphone and tablet devices, there is one single orientation event
named orientationchange. This event triggers
when the device is rotated vertically or horizontally. To determine what
direction the device is rotated, you can access the orientation property,
which provides a read-only value of portrait or
landscape. Binding to the
orientationchange event requires you to target
the body element and then use the
bind method to bind the event (see Listing 11).
Listing 11. Binding the
orientationchange event to the body element
$(document).ready(function(){
$('body').bind('orientationchange', function(event) {
alert('orientationchange: '+ event.orientation);
});
});
|
It's also important to bind the event after the document is ready.
Otherwise, you receive inconsistent results because the
body element may not be available at the time
of binding. You can also take this code a step further by triggering the
orientationchange event when the document is
ready (see Listing 12).
Listing 12. Triggering the
orientationchange event when the document is ready
$(document).ready(function(){
$('body').bind('orientationchange', function(event) {
alert('orientationchange: '+ event.orientation);
});
$('body').trigger('orientationchange');
});
|
Triggering the event when the document is ready allows you to determine the orientation when the web page is initially loaded. This is especially useful in situations where you are displaying content based on the current orientation of the device in use. The orientation values are also accessible via CSS because they are added to the HTML element within your web page. These powerful features allow you to modify the layout of your content based on the orientation of the device.
jQuery Mobile includes scroll events that trigger when the user scrolls the
web page. The first event is the scrollstart
event, which triggers when a page scroll begins. Listing 13 shows how you
can bind to this event and add custom JavaScript code that runs when
scrolling begins.
Listing 13. Binding to the
scrollstart event
$(document).ready(function(){
$('body').bind('scrollstart', function(event) {
// Add scroll start code here
});
});
|
Another event, named scrollstop, applies when
the page scroll stops. As you can see in Listing 14, binding to the
scrollstop event works just as the
scrollstart binding does.
Listing 14. Binding to the
scrollstop event
$(document).ready(function(){
$('body').bind('scrollstop', function(event) {
// Add scroll stop code here
});
});
|
Binding to both of these events must be done when the document is
officially ready. This ensures that the body
element exists and can successfully be bound to the events. As an example,
both of these events could be useful in running JavaScript code that
reveals options lower on the web page as the page is scrolling—what
is called lazy loading, where images are not loaded when the web
page originally loads. This keeps the page load time short while still
providing the same visual appeal when the content is accessed.
The following functionality is possible by using the exposed methods available through the jQuery Mobile API:
- Changing pages programmatically
- Silently loading pages
- Working with utility methods
Changing pages programmatically
One of several exposed methods in the jQuery Mobile framework is one that
allows you to change pages programmatically in addition to the default use
of hyperlinks and form submissions. All the visuals that occur, from page
loading to page transition, are included when you change pages
programmatically. Listing 15 shows how to change the page using the
$.mobile object's
changePage method.
Listing 15. Changing the page using the
changePage method
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="jquery.mobile.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#my-page").live('pagecreate', function(event) {
$("#alt-link").bind("click", function(event) {
$.mobile.changePage("page-2.html");
});
});
</script>
<script type="text/javascript" src="jquery.mobile.js"></script>
</head>
<body>
<div data-role="page" id="my-page">
<div data-role="content">
<ul data-role="listview" id="my-list"></ul>
</div>
</div>
<script type="text/javascript">
$('#my-list').append('<li><a href="page-2.html">Link to another page</a></li>');
$('#my-list').append('<li><a href="#" id="alt-link">Link to another
page programmatically</a></li>');
</script>
</body>
</html>
|
There is one required argument, which is named
to. This argument can be a string or an object.
The to argument can be an absolute or relative
URL. The object argument needs to be a jQuery collection object—in
other words, an inline element that is being used as an additional page.
There are also a number of optional properties that you can pass as an
object:
transitionreversechangeHashrolepageContainertypedatareloadPage
Listing 15 doesn't use any of the optional arguments. Rather, it simply passes the name of another HTML file.
To use the changePage method, you need to do a
few things. First you must create a div element
with a data-role value of
page and add an ID to it. With this ID, you
need to add the pagecreate event rather than
jQuery's document.ready. Now you can add your
click events. jQuery Mobile recommends that you bind a link rather than
calling the click event directly. And, finally,
you can change the page using the changePage
method.
Another great $.mobile object method is
loadPage. You can use the
loadPage method to load external pages without
displaying them. This is a useful way to preload pages so that they
display more quickly when the user clicks a link. To use this method, you
need to write code much like when you use the
changePage method. First you need a
page element with an ID so you can access it to
bind the pagecreate event. Then when the
pagecreate event triggers, you can call the
loadPage event (see Listing 16).
Listing 16. Preloading pages using the
loadPage method
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="jquery.mobile.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#my-page").live('pagecreate', function(event) {
$.mobile.loadPage("page-2.html");
});
</script>
<script type="text/javascript" src="jquery.mobile.js"></script>
</head>
<body>
<div data-role="page" id="my-page">
<div data-role="content">
<ul data-role="listview" id="my-list">
<li><a href="page-2.html">Link to another page</a></li>
</ul>
</div>
</div>
</body>
</html>
|
The loadPage method includes a required URL
argument that can be a string representing a relative or absolute URL, or
you can pass an object. There is also an optional argument that accepts an
object with one or more of the following properties:
rolepageContainertypedatareloadPageloadMsgDelay
There are a number of built-in utility methods that provide useful functionality when developing a website using the jQuery Mobile framework (see Table 2).
Table 2. Current built-in utility methods for jQuery Mobile
| Method | Description |
|---|---|
$.mobile.path.parseUrl | Parses a URL into an object with 16 properties |
$.mobile.path.makePathAbsolute | Converts relative file or directory to an absolute path |
$.mobile.path.makeUrlAbsolute | Converts a relative URL to an absolute URL |
$.mobile.path.isSameDomain | Compares two URLs |
$.mobile.path.isRelativeUrl | Determines if a URL is relative |
$.mobile.path.isAbsoluteUrl | Determines if a URL is absolute |
$.mobile.path.base | Works with the generated base element |
The jQuery Mobile framework is simple to use, but don't let its simplicity fool you. There is much happening behind the scenes, and there are many ways to add custom functionality to provide powerful mobile websites and applications. By tapping into the API, you can tell the framework how to behave by default, speed up page load by working with exposed methods, and even tie into every interaction that occurs on the client side.
| Description | Name | Size | Download method |
|---|---|---|---|
| Sample jQuery Mobile web page with API code | jquery-mobile-api.zip | 115KB | HTTP |
Information about download methods
Learn
- Check out the current
documentation for the jQuery Mobile framework.
- Learn more about jQuery on developerWorks.
- In the developerWorks
Web development zone, find hundreds of how-to articles and tutorials, as well as downloads, discussion
forums, and a wealth of other resources for web developers.
- Check for mobile updates on the
developerWorks Mobile development blog.
- You'll find hundreds more mobile-related articles on developerWorks.
- Stay current with developerWorks technical events and webcasts focused on a variety
of IBM products and IT industry topics.
- Attend a free developerWorks Live! briefing to get up-to-speed quickly on
IBM products and tools, as well as IT industry trends.
- Watch developerWorks on-demand demos ranging from product installation
and setup demos for beginners, to advanced functionality for experienced
developers.
- Follow developerWorks on
Twitter.
Get products and technologies
- Download and
reference the jQuery Mobile
JavaScript and CSS files.
- Download and try
the IBM Mobile Technology Preview, a set of code samples and services
to help you get started building mobile applications that extend and
integrate into the enterprise. The preview includes a RESTful notification
service; PhoneGap, an open source framework for building hybrid mobile
apps; a lightweight WebSphere Application Server runtime; and sample code
to let you see how it all works.
-
IBM WebSphere Application Server Feature Pack for Web 2.0 and
Mobile includes the IBM Dojo 1.7 Toolkit, new mobile and rich
Internet application (RIA) building blocks, and a Dojo-based diagram
component. With accompanying Rational tools, the Feature Pack helps you
take WebSphere applications developed originally for desktop browsers and
adapt and deploy them to mobile devices.
-
Evaluate
IBM products in the way that suits you best: Download a product
trial, try a product online, use a product in a cloud environment, or
spend a few hours in the SOA Sandbox learning how to implement Service Oriented
Architecture efficiently.
Discuss
- Get involved in the developerWorks
community. Connect with other developerWorks users while exploring
the developer-driven blogs, forums, groups, and wikis.

Kris Hadlock has been a contract web developer and designer since 1996. He has worked on projects for companies such as SPIN Magazine, IKEA, United Airlines, JP Morgan Chase, GoDaddy Software, and Fire Mountain Gems. He is the author of Ajax for Web Application Developers (Sams) and The ActionScript Migration Guide (New Riders) as well as a featured columnist and writer for numerous websites and design magazines, including Peachpit.com, InformIT.com, and Practical Web Design magazine. Kris is also the founder of www.studiosedition.com, a web design and software development studio specializing in fusion of form and function.



