Use the jQuery Mobile API for fine-grained custom control

Extend jQuery Mobile by setting global options, hooking into interaction events, and working with exposed methods

The jQuery Mobile framework is a quick and easy way to create mobile websites. However, you might not know that the framework has a decent API that you can use to extend the basic functionality. This article provides an overview of some of the most useful features in the API and gives you working code examples throughout.

Share:

Kris Hadlock, Web Developer/Designer, Studio Sedition

Photo of Kris HadlockKris 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.



10 January 2012

Also available in Chinese Russian Vietnamese Portuguese

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).

Pressed for time? (Don't answer that.)

Instantly add pre-built, managed, and scalable cloud services to your mobile apps with the Mobile cloud services on IBM Bluemix.

Choose from popular services for shared data, push notifications, and server-side scripting along with SDKs for Android, iOS, and Node.js. Sign up for a free Bluemix cloud trial and learn more.

Global options

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.

Creating custom namespaces

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.

Page initialization

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

Touch 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
EventDescription
tapTriggers when someone quickly taps the screen.
tapholdTriggers when someone taps the screen and continues to touch the screen for about one second.
swipeTriggers 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.
swipeleftTriggers when the web page is dragged to the left.
swiperightTriggers 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.

Orientation events

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.

Scroll events

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.


Working with exposed methods

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:

  • transition
  • reverse
  • changeHash
  • role
  • pageContainer
  • type
  • data
  • reloadPage

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.

Silently loading pages

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:

  • role
  • pageContainer
  • type
  • data
  • reloadPage
  • loadMsgDelay

Working with utility methods

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
MethodDescription
$.mobile.path.parseUrlParses a URL into an object with 16 properties
$.mobile.path.makePathAbsoluteConverts relative file or directory to an absolute path
$.mobile.path.makeUrlAbsoluteConverts a relative URL to an absolute URL
$.mobile.path.isSameDomainCompares two URLs
$.mobile.path.isRelativeUrlDetermines if a URL is relative
$.mobile.path.isAbsoluteUrlDetermines if a URL is absolute
$.mobile.path.baseWorks with the generated base element

Conclusion

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.


Download

DescriptionNameSize
Sample jQuery Mobile web page with API codejquery-mobile-api.zip115KB

Resources

Learn

Get products and technologies

Discuss

  • Get involved in the developerWorks community. Connect with other developerWorks users while exploring the developer-driven blogs, forums, groups, and wikis.

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Mobile development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Mobile development, Web development, Open source
ArticleID=784676
ArticleTitle=Use the jQuery Mobile API for fine-grained custom control
publish-date=01102012