I’m developing a mobile website using the jQuery Mobile library. I have a header, a footer and a content area on the main page, and any links are loaded into the content area using the following code:
$("a").click(function() {
var toLoad = $(this).attr('href');
// Loading image
$('#content-body').html('<table class="loader"><tr><td><img src="<?php echo SITE_ROOT; ?>/img/ico/loader.gif" /></td></tr></table>');
$('#content-body').load(toLoad);
This works fine, except that the jQuery Mobile styles don’t apply to content included this way. For example, the home page includes buttons:
<a href="?Inventory" data-role="button">Inventory</a>
But when I load that page asynchronously into the content div, the links do not appear as buttons. Is there any way to tell jQuery Mobile to apply the mobile styles every-time #content is reloaded?
You sure can. You want to use
.trigger('create')to initialize any jQuery Mobile widget:Note that you call
.trigger('create')on the parent element of the widget you want to initialize. Also note that since you are loading content through an asynchronous function you will need to call.trigger('create')in the callback function for your.load()call so that the elements to initialize are actually present when you try to initialize them.Also you can sometimes run into an issue where the widget has been initialized but then you changed it’s HTML and want to refresh the widget instead. There are functions to do this such as:
.listview('refresh'),.slider('refresh'), etc.I just answered a question regarding widgets needing to be initialized or refreshed: how to refresh jquery mobile listviews
Also you will want to change that
.click()to a.delegate()so the links that are loaded via AJAX will also have this event handler attached: