Add Panel Dynamically

In compliance with DRY principle, jQuery Mobile 1.4 offers external toolbars, panels and popups to be accessed from any page. Unlike successor versions, each page should contain its’ own toolbars, panels and popups. However, those widgets should be initialized manually since they are placed outside pageContainer. Hence, upon framework initialization, they are untouched.

I would like to share some methods of adding external or internal panels dynamically. This can be done in many ways, depending on when you want to inject a panel or replace existing one.

Note: External widgets don’t inherit themes, hence, data-theme should be added.


Since this event fires once, so there is no need to check whether a panel does exist in DOM before adding it dynamically. However, note that at this stage $(" :mobile-pagecontainer ") or $.mobile.pageContainer isn’t defined yet. The default $(" :mobile-pagecontainer ") is $(" body ").

After adding the panel, it should be initialized as well as the contents within it. In case other widgets – e.g. listview – are used, they should be initialized by calling .enhanceWithin() on the panel (parent container).

<script src="jquery.js"></script>
    /* add panel */
    $( document ).on( "mobileinit" , function() {
        var panel = '<div>panel</div>';
        $( "body" ).prepend( panel ); /* or .append */
<script src="jquery-mobile.js"></script>
    /* initialize panel and contents */
    $(function() {
        $( "[data-role=panel]" ).panel().enhanceWithin(); /* or #panelID or .class */



This event fires once but per page, so you need to bind it one time only .one() and not .on(), otherwise, a panel will be added every time that event fires.

The only difference between mobileinit and pagebeforecreate is that $.mobile.pageContainer is defined, and you can initialize panel straightaway.

$(document).one('pagebeforecreate', function () {
    var panel = '<div>panel</div>';
    $.mobile.pageContainer.append( panel );
    $( "[data-role=panel]" ).panel().enhanceWithin();


Load panel from an external file (Ajax)

Let’s say you have endless number of customized panels based on user’s preference and you have those panels saved in external files on your server. When user “X” logs in, you want to load a specific panel directly from server. In this case use $.get() (Ajax) to load them.

$.get("URL", function (data) {
}, "html");


Buy Me A Coffee :) @


One thought on “Add Panel Dynamically

Drop me a line or two ;)

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s