The initialization of a mobile jquery widget on a page gives & ldquo; Unable to read property 'jQuery & hellip;' Of indefinite & rdquo;


Fiddle Example

The site has 2 (or more) pages defined in HTML like this:

<div id="page1" data-role="page">
    <div data-role="content" id="page1-content">
        <a href="#page2" data-role="button">Next Page</a>

<div id="page2" data-role="page">
    <div data-role="content" id="page2-content">
        <a href="#page1" data-role="button">Go Back</a>

In Javascript - I am at once initializing everything:

    $('#page1-content, #page2-content').each(function(){
        var ul = $('<ul>');
        $.each(['one','two','three'], function(item){
            ul.append('<li><a href="#">'+item+'</a></li>');

But the page only initializes the list view on the 1st page, and the list view on the 2nd (and not currently visible) page does not initialize and gives me an error.

Cannot read property 'jQuery19107783124386332929' of undefined

What am I doing wrong?

I really want to be able to start fetching the data and at least create the DOM in every page at once in the beginning, rather than waiting till the user clicks "Next Page".

Also - the list view on the first page is overlapping the "Next" button. I see this overlapping often and would like to fix/understand this too.

Page data-role=page in jQuery Mobile passes through different stages, as shown in the diagram below.

Image / diagram source:

Enhancing widgets manually should be called on active page only, otherwise it will result in a error.

To do add fresh elements on different pages, you need to do this when pagecreate or pagebeforecreate events occur, without the need to call any enhancement method. As the widget will be auto-initialized/enhanced during that stage.

Also, you have a mistake in your code where you didn't close ul tag. However, this didn't cause the error.

The below code shows how to add elements to different pages without the need to call any enhancement method manually.

$(document).on("pagecreate", "[data-role=page]", function (e) {
    var ul = $('<ul data-role="listview" data-inset="true"></ul>'),
        html = '';
    $.each(['one', 'two', 'three'], function (item) {
        html += '<li><a href="#">' + item + '</a></li>';
    $('[data-role=content]', this).append(ul);