Tuesday, September 1, 2015

ADD PANEL DYNAMICALLY



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.

mobile init

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

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

page before create

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) {
    $.mobile.pageContainer.append(data);
    $("[data-role=panel]").panel().enhanceWithin();
}, "html");

java script 


$(document).on("pagecreate", function () {
    $("#load").one("click", function () {
        /* for demo */
        $(this).remove();
        $.mobile.loading("show", {
            theme: "b",
            text: "Loading panel..",
            textVisible: true,
            textonly: false
        });
        /* load panel then open it */
        $.get("/Palestinian/GYNLy/show/", function (data) {
            $.mobile.pageContainer.append(data);
            $("[data-role=panel]").panel().enhanceWithin();
        }, "html").done(function () {
            $.mobile.loading("hide");
            $("[data-role=panel]").panel("open");
        });
    });
});

Popular Posts