How to add <ons-tab> dynamicaly with javascript

  • I try to customise the <ons-tab> depending on json string. For example if you are admin, you have an additional admin tab.
    So I have a json string and I try to create <ons-tab> element based on the json field.
    I don’t know how to set it properly because when use “$(’#tabbar1’).append” command tabs seems not properly set.

    You can try this code:

        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, user-scalable=no">
        <script type="text/javascript" src="components/loader.js"></script>
        <script type="text/javascript" src="components/monaca-jquery/jquery.js"></script>
        <script type="text/javascript" src="components/monaca-onsenui/js/onsenui.js"></script>
        <link rel="stylesheet" href="components/monaca-onsenui/css/onsenui.css">
        <link rel="stylesheet" href="components/monaca-onsenui/css/onsen-css-components.css">
        <script type="text/javascript">    
        function getmyjson() {  
            var payload = '{"data":[{"id":"1","title":"ONE"},{"id":"2","title":"TWO"}]}';
            jsondata = JSON.parse(payload);
            $.each(, function(i,item){               
                $('#tabbar1').append('<ons-tab page="#" label="' +  item.title + '" icon="md-settings" active-icon="md-face"></ons-tab>');               
        $(document).ready(function() {
          <ons-tabbar swipeable position="auto" id="tabbar1">
            <ons-tab page="tab1.html" label="Tab 1" icon="ion-home, material:md-home" active></ons-tab> 
            <ons-tab page="#" label="ZERO" icon="md-settings" active-icon="md-face"></ons-tab>
        <template id="tab1.html">
          <ons-page id="Tab1">

    You will see something unexpected where tabs are not in the “tabbar1” element.

  • Onsen UI

    @joyeux86 This use case is not officially supported so there is no nice API for it. However, I think you can make it work easily. You need to know that ons-tabbar element is compiled at some point and its inner HTML structure is changed. You don’t want to attach the new tab to ons-tabbar but to the child that contains .tabbar class ('#tabbar1 .tabbar' in your example I guess). Also, do not attach the tabbar as the last child (appendChild), but to the second last. Something like tabbar.insertBefore(tab, tabbar.lastChild) should work (or its equivalent in jQuery).

Log in to reply