MarkO MarkO - 2 months ago 20
jQuery Question

jquery mobile Dynamically Injecting Pages

I'm using jQuery mobile and currently build a menu on the fly using the code below. I now need to create actual pages for menu items as my next step. I have been looking at jQuery Mobile and Dynamic Page Generation and think this is something I 'could' use to achieve this. I have read the Dynamic Page Generation docs and don't understand how I could fit this into my current code or even if its right for what I need to achieve.

I you can see below I have the ID and page name etc already when I build my menu output for the home page, could someone show me an example of how I now dynamically build the html pages needed using jquery for these menu items? Thank you.

$.each(siteData["pages"], function(i,v) {
$.mobile.activePage.find('[data-role=content]').append('' +
'<a href='+ v["id"] + ' data-role="button">' + v["name"] + '</a>').trigger('create');

// NOW I HAVE THE MENU LETS CREATE THE ACTUAL PAGES INSIDE HERE TOO
});


Current markup menu items created inside navlist:

<div data-role="page" id="index">
<div data-theme="a" data-role="header">
</div>

<div data-role="content" class="navlist">
</div>

<div data-role="footer">
</div><!-- /footer -->
</div>


So now for each item I need the to generate the markup for each item using jquery.

UPDATE: so based on suggestion I tried something like this, but it does not work.

$.each(siteData["pages"], function(i,v) {
$.mobile.activePage.find('[data-role=content]').append('' +
'<a href='+ v["id"] + ' data-role="button">' + v["name"] + '</a>').trigger('create');



// Prepare your page structure
var newPage = $("<div data-role='page' id=v[id]><div data-role=header>" +
"<a data-iconpos='left' data-icon='back' href='#' data-role='button' " +
"data-rel='back'>Back</a><h1>Dynamic Page</h1></div><div data-role=content>Stuff here</div></div>");

// Append the new page info pageContainer
newPage.appendTo($.mobile.pageContainer);

// Move to this page by ID '#page'
$.mobile.changePage('#'+v["id"]);


});

Answer

Here is a simple way of creating new pages dynamically.

Working example

// Prepare your page structure
var newPage = $("<div data-role='page' id='page'><div data-role=header><a data-iconpos='left' data-icon='back' href='#' data-role='button' data-rel='back'>Back</a><h1>Dynamic Page</h1></div><div data-role=content>Stuff here</div></div>");

// Append the new page into pageContainer
newPage.appendTo($.mobile.pageContainer);

// Move to this page by ID '#page'
$.mobile.changePage('#page');
Comments