Creating templated/persistant header/footer template in jQuery Mobile and PhoneGap

I’ve been trying to tackle this problem for a few days now and I’ve gotten really close to the solution. I use the following HTML:

<body>
    <div data-role="page" id="page">

        <div data-role="header">
            <h1 id="title">Title</h1>
        </div><!-- /header -->

        <div data-role="content" id="content">  
            <p>Loading...</p>
        </div><!-- /content -->

        <div data-role="footer" id="footer" data-position="fixed">
            <div data-role="navbar" id="navbar">
            </div>
        </div><!-- /footer -->
    </div><!-- /page -->
</body>

And I’ve created the following functions to load the menu/content using ajax:

$(document).on('pageinit', "#page", function() {
    // for example: displayFooter();
    loadContent("main");
    loadMenu("default");
});

function loadContent(location) {
    return $('#content').load("views/content/"+location+".html", function() { 
        $(this).trigger('create');
    });
}
function loadMenu(location) {
    $("#menu").remove();
    $("#navbar").remove();

    $("#footer").html('<div data-role="navbar" id="navbar">');
    $("#navbar").html('<ul id="menu"></ul>');

    $("#menu").load("views/menus/"+location+".html", function() { $("#menu").parent().navbar(); });

    return true;
}

The .trigger('create'); and .navbar(); are the methods required to keep the JQM styling correct, however, there’s still one little bug. The position of the menu (which is set using css top: …px) is sometimes not correct and moves itself to the correct position after the first tap. Really close though!

Edit: By setting #footer to position: fixed; the minor bug I mentioned above is gone. Also, it’s easy to make a method that calculates the top (in px) for the #footer if the position caused by the top value by JQM is incorrect.

Leave a Comment