Thursday, 28 November 2013

JQuery Mobile panels and headers in multiple pages

In a jqm multipage project I often want to use a header, footer or navigation panel across several pages. How do I do this without repeating the markup for each page? Well, my solution is to write the markup only once on the main page, and then on the pagebeforecreate event clone it to all the other pages.

Take a nav panel for example:
<div data-role="page" id="index">
<div data-role="panel" data-position-fixed="true" data-theme="a" id="nav-panel">
            <ul data-role="listview" data-theme="a" class="nav-search">
                <li data-icon="delete"><a href="#" data-rel="close">Close menu</a></li>
                    <li><a href="#" data-destination="#home">Home</a></li>
                    <li><a href="#" data-destination="#search">Search</a></li>
                    <li><a href="#" data-destination="#about">About</a></li>
 <!-- etc.... -->
And then in subsequent pages I add a div with a suitable classname to identify it:
<div data-role="page" id="search">
        <div class="navPanelChild"></div>
<!-- etc.... -->
And then on the pagebeforecreate event of the first page of the app I clone the nav panel and replace all the child containers with it:
$(document).delegate("#index", "pagebeforecreate", function () {
      var navpanelCopy = $( "#nav-panel" ).clone();
      $( ".navPanelChild" ).replaceWith(navpanelCopy);


  1. This is exactly what I need to do, but I can't figure out what goes where. It would be nice to see all the code on one page - looking at your line numbers there are 3 different pages. Thanks.

    1. Hi Paul the line numbers are rendered by the plugin I use on this blog, they are not from my orginal code. I have removed them now to avoid confusion. In my solution I have two main files - a single HTML file with multiple pages (data-role="page"), and a javascript file that unobtrusively does all the hard work. The first block of code you see is from my first 'page' in the HTML file. The second block of code is found in subsequent pages of the HTML, where required. The javascript is in my javascript file and picks up on the pagebeforecreate event.


Comments are moderated, so you'll have to wait a little bit before they appear!