Configuring jQuery Mobile, Handling Events, and Building Custom Themes
To adjust jQuery Mobile behavior, attach a handler to the mobileinit event. Place this script before the framework's JavaScript file:
<script src="img/jquery.js"></script>
<script src="img/custom-config.js"></script>
<script src="img/jquery.mobile.js"></script>
The callback receives the $.mobile object, which holds all configurable settings. You can change a single property:
$(document).on('mobileinit', function() {
$.mobile.defaultPageTransition = 'fade';
});
Alternatively, use $.extend to modify multiple options at once. Key settings include:
ns– data-attribute namespace (default empty).activeBtnClass/activePageClass– classes for the active button or page.ajaxEnabled– set tofalseto disable AJAX navigation and form handling.allowCrossDomainPages– enable cross-domain page loads (rarely used outside PhoneGap).autoInitializePage– whether jQuery Mobile auto-initializes on load.defaultDialogTransition/defaultPageTransition– animation for dialogs and pages. Options:fade,flip,pop,slide,slidedown,slideup.gradea– custom function defining "grade A" browsers.hashListeningEnabled– listen tolocation.hashchanges.ignoreContentEnabled– must betruewhen usingdata-enhance="false"on containers.linkBindingEnabled– disable global link click interception.loadingMessage/loadingMessageTextVisible/loadingMessageTheme– customize the loading indicator.minScrollBack– scroll position restore threshold (default 150).pageLoadErrorMessage/pageLoadErrorMessageTheme– error dialog text and theme.pushStateEnabled– use HTML5 pushState for navigation.subPageUrlKey– prefix for virtual page IDs in URLs.
To prevent automatic enhancement of specific input types, assign a selector string to $.mobile.page.prototype.options.keepnative.
Physical Events
jQuery Mobile provides normalized touch and motion events. Common ones:
tap– quick touch.taphold– sustained touch (~1 second).swipe,swipeleft,swiperight– directional finger movement. There is no vertical swipe event.scrollstart/scrollstop– scroll begin and end.orientationchange– device rotation (native event).vclick,vmousedown,vmouseup,vmousemove,vmousecancel,vmouseover– virtual mouse events that unify touch and click.
Example: tap and taphold
$('body').on('tap', function() {
$('#status').text('Tap detected');
});
$('body').on('taphold', function() {
$('#status').text('Tap-hold detected');
});
Example: swipe-based navigation
$('body').on('swipeleft swiperight', function(e) {
var activePage = $.mobile.activePage[0];
var direction = e.type;
if (activePage.id === 'first' && direction === 'swipeleft') {
$.mobile.changePage('#second');
} else if (activePage.id === 'second' && direction === 'swiperight') {
$.mobile.changePage('#first');
}
});
Page Lifecycle Events
jQuery Mobile emits a rich sequence of events during page transitions and initialization:
- Load:
pagebeforeload,pageload,pageloadfailed - Change:
pagebeforechange,pagechange,pagechangefailed - Transition:
pagebeforeshow,pageshow,pagebeforehide,pagehide - Init:
pagebeforecreate,pagecreate,pageinit - Remove:
pageremove - Layout:
updatelayout
pagebeforeload and pagebeforechange can prevent the subsequent action programmatically. pagebeforecreate fires before the framwork enhances markup, allowing manual DOM manipulation. pagecreate runs after the page is in the DOM but before enhancement; it is the recommended place for custom widget setup. pageinit replaces $(document).ready for dynamic pages, since ready only fires once on the initial load.
Log all page events for debugging:
$(document).on('pagebeforeload pageload pageloadfailed pagebeforechange pagechange pagechangefailed pagebeforeshow pagebeforehide pageshow pagehide pagebeforecreate pagecreate pageinit pageremove updatelayout', function(e) {
console.log(e.type);
});
Page Methods and URL Utilities
$.mobile.activePage references the current page. Programmatic navigation uses $.mobile.changePage(target, options), where target can be a URL string or a jQuery object. Supported options: transition, reloadPage, showLoadMsg, data, changeHash, etc.
$('#goBtn').on('click', function() {
$.mobile.changePage('detail.html', { transition: 'flip' });
});
The lower-level $.mobile.loadPage() accepts similar parameters with a loadMsgDelay option. Loading spinners can be shown or hidden via $.mobile.showPageLoadingMsg() and $.mobile.hidePageLoadingMsg().
Path utilities live under $.mobile.path:
isAbsoluteUrl(url)/isRelativeUrl(url)isSameDomain(url1, url2)makePathAbsolute(relative, absolute)makeUrlAbsolute(relative, absolute)parseUrl(url)– returns an object withhash,host,pathname,search, and derived properties (domain,directory,filename,hrefNoHash, etc.).
Dynamic Content and Widget Refresh
When adding content after page creation, jQuery Mobile does not re-apply enhancements automatically. Use the widget method refresh to restyle the element:
$('#addBtn').on('click', function() {
var newItem = $('#itemInput').val().trim();
if (newItem === '') return;
$('#myList').append('<li>' + newItem + '</li>');
$('#myList').listview('refresh');
});
For a completely new list, call .listview() without arguments:
$('#container').append('<ul id="freshList" data-role="listview"><li>Item</li></ul>');
$('#freshList').listview();
Similar widget methods exist for buttons (.button()), collapsibles, etc.
Building a Dynamic Notekeeper App
Consider a simple note-taking app that stores data using localStorage and displays notes in a listview. The app uses a single HTML file and an application.js.
Pattern – wrap code in a self-invoking function to avoid global pollution:
$(function(){
var Notekeeper = {};
(function(app){
var $title = $('#title');
var $note = $('#note');
var $list = $('#notesList');
app.init = function(){
app.bindEvents();
app.loadNotes();
};
app.bindEvents = function(){
$('#addBtn').on('click', function(e){
e.preventDefault();
app.saveNote($title.val(), $note.val());
});
};
app.saveNote = function(title, body){
var notes = app.readNotes();
var key = title.replace(/\s/g, '-');
notes[key] = body;
localStorage.setItem('notes', JSON.stringify(notes));
$title.val('');
$note.val('');
app.renderList();
};
app.readNotes = function(){
var json = localStorage.getItem('notes');
return json ? JSON.parse(json) : {};
};
app.renderList = function(){
var notes = app.readNotes();
var html = '<li data-role="list-divider">Your Notes</li>';
if ($.isEmptyObject(notes)){
html += '<li>No notes yet</li>';
} else {
for (var key in notes){
html += '<li><a href="#details?title=' + key + '">' + key.replace(/-/g, ' ') + '</a></li>';
}
}
$list.html(html).listview('refresh');
};
app.loadNotes = function(){
app.renderList();
};
app.init();
})(Notekeeper);
});
Deleting a note works similarly: remove the key from the object, write back to localStorage, and refresh the list. The detail page can be built dynamically and injected into the DOM using $.mobile.changePage().
Theming and Custom Icons
jQuery Mobille ships with five swatches (A–E). Each swatch is a set of CSS rules for bar, content block, and button appearence. The data-theme attribute applies a swatch to an element or inherits from the parent. The global active state uses .ui-btn-active and can be overridden.
To create a custom theme, use the ThemeRoller tool. Import the default theme, remove unused swatches, drag-and-drop colors onto the preview, and fine-tune via the inspector. Always produce at least three swatches (A–C). Download the ZIP and include the themes/ folder with your project.
Adding a custom icon: design two transparent PNGs at 18×18 (low-res) and 36×36 (high-res) pixels. jQuery Mobile uses a CSS sprite map for icons. For a single custom icon, define:
.ui-icon-custom-note {
background-image: url("themes/images/custom-note-white-18.png");
}
@media only screen and (-webkit-min-device-pixel-ratio: 2) {
.ui-icon-custom-note {
background-image: url("themes/images/custom-note-white-36.png");
background-size: 18px 18px;
}
}
Apply the icon with data-icon="custom-note" on any button.
Using these techniques, you can fully tailor jQuery Mobile applications—configuring behaviour, handling physical and page events, refreshing dynamic content, and styling with custom swatches and icons.