Dynamic Content

If we are using dynamic content, such as a database-driven website, it’s possible that we don’t want to create jQuery Mobile documents on the fly and we just want to use JavaScript and AJAX to change, show, and hide information in our webapp.

Warning

When you are using JavaScript-based elements instead of semantic markup you may have problem with non-jQuery Mobile compatible browsers. If you are targeting smartphones and tablets you may not have any problem.

Creating Pages

Can we create pages on the fly? We know that a page is just a div element with a proper data-role, so our first thought is that we can make it work. Let’s try and see what it happens. We are going to create a basic page that will create four pages on the fly using JavaScript:

<div data-role="page">
        <div data-role="header">
    <h1>Dynamic page</h1>
    </div>
        <div data-role="content">
        <a id="button1" href="javascript:addPages()" data-role="button">Add Pages</a>
        <ul id="list1">

        </ul>
    </div>
</div>

Then in a script we define the function to create dynamic pages and add buttons to transition to them:

function addPages() { for (var i=1; i<5; i++) { var page = $("<div>").jqmData("role", "page").attr("id", "page" + i); // header $("<div>").attr("data-role", "header").append($("<h1>") .html("Page " + i)).appendTo(page); // content $("<div>").attr("data-role", "content").append($("<p>") .html("Contents for page " + i)) .appendTo(page); $("body").append(page); $("<li>").append($("<a>").attr("href", "#page"+i).html("Go ...

Get jQuery Mobile: Up and Running now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.