Add Panel Dynamically

jQuery Mobile

by Omar X

HTML

<div data-role="page" id="p1" data-theme="b">
    <!-- header -->
    <div data-role="header" data-theme="d" data-position="fixed"> <a href="#" data-role="button" data-inline="true" data-icon="info" data-iconpos="notext" data-iconshadow="false" data-theme="e" class="ui-icon-nodisc toggle-panel"></a>

         <h1>Header</h1>

    </div>
    <!-- content -->
    <div data-role="content">
<a data-role="button" href="#" id="create" data-icon="plus">Create a Panel</a>

    </div>
    <!-- footer -->
    <div data-role="footer" data-position="fixed" data-theme="d" class="ui-bar">
<a href="#about" data-rel="popup" data-position-to="window" data-role="button" data-inline="true" data-transition="flip" data-icon="info" data-theme="e">About</a>
    </div>
    <!-- About Author Popup -->
    <div data-role="popup" id="about" data-overlay-theme="a" data-theme="c" data-dismissible="false" style="max-width:300px;" class="ui-corner-all"> <a href="#" data-rel="back" data-role="button" data-theme="a" data-icon="delete" data-iconpos="notext" class="ui-btn-right">Close</a>

    <div data-role="header" class="ui-header ui-bar-c">
         <h1>About Author</h1>

    </div>
    <div data-role="content" data-theme="d" class="ui-corner-bottom ui-content">
        <p>Demonstration was created by <b>Omar</b> for <a href="#">StackOverflow.com</a>.
            <br/>
            <br/>For more examples on jQuery Mobile, click the button below.</p> <a href="http://stackoverflow.com/users/1771795/omar" data-role="button" data-theme="c" target="_blank">Profile</a>

    </div>
</div>
    <!-- /About -->
</div>
<!-- page -->

JavaScript

$(document).one('click', '#create', function () {
    var panel = '<div data-role="panel" id="mypanel" data-position="left" data-display="reveal" data-dismissible="false" data-theme="c"><h1>Panel</h1></div>';
    if ($('[data-role=panel]').length === 0) {
        $('[data-role=header]').before(panel);
    }
    $('[data-role=page]').trigger('pagecreate');
    setTimeout(function () {
        $('#mypanel').panel('open');
        $('#create').hide('slow');
    }, 200);
});

$(document).one('panelcreate', '#mypanel', function () {
    $('div.ui-panel-inner').append('<div class="panel-content" />');
    $('div.panel-content').append('<a data-role="button" href="#" id="add" data-theme="e" data-icon="grid">Add Contents</a> <a data-role="button" href="#" class="toggle-panel" data-theme="a" data-icon="delete">Close</a>').trigger('create');
});

$(document).on('click', 'a.toggle-panel', function () {
    $('#mypanel').panel('toggle');
});

$(document).on('click', '#add', function () {
    var listview = '<ul data-role="listview" data-inset="true"><li><a href="#">Acura</a></li><li><a href="#">Audi</a></li></ul>';
    $('div.panel-content #add').after(listview);
    $('[data-role=page]').trigger('pagecreate');
});