0

I am trying to learn JS and some JS templating libraries, but I've some difficulties using them. I'm trying to build a page which will load dynamically content from json file using ajax and then create tabs with content.

JSON file structure is something like

"id": "0",  
"name": "Some Title",
"content": "<h1>Hello</h1>"

Here is my html file:

<div class="container">
    <ul class="nav nav-tabs" id="tabsId">
        <script id="tabs-template" type="text/x-handlebars-template">
            {{#each Tabs}}
                <li data-tab-content={{Id}}><a href="#">{{Name}}</a></li>
            {{/each}}
        </script>
    </ul>
    <div id="tabsContentId">
    <script id="tabs-content-template" type="text/x-handlebars-template">
        {{#each Tabs}}
            <div class="tab-content" data-tab-content="{{Id}}">{{Content}}</div>
        {{/each}}
    </script>
    </div>
</div>

And here is my JS:

$(function() {
    sendRequest();
});

function sendRequest () {
    $.ajax({
        url         : '../data/tabs.json',
        type        : 'GET',
        dataType    : 'json',
        success     : function( response ) {
            createTabs(response);
            createTabsContent(response);
        },
        error : function( xhr, status, errorThrown ) {
            console.log( 'ConsoleStatus: ' + status );
            console.log( 'ConsoleError: ' + errorThrown );
        },
    });
}

function createTabs( data ) {
    var templateSource  = $('#tabs-template').html(),
        template        = Handlebars.compile( templateSource ),
        tabsContainer   = template( data );
    $('#tabsId').html( tabsContainer );
}

function createTabsContent( data ) {
    var templateSource  = $('#tabs-content-template').html(),
        template        = Handlebars.compile( templateSource ),
        tabsContainer   = template( data );
    $('#tabsContentId').html( tabsContainer );
}

How can I load tab content onclick?

2
  • What problems are you facing actually ? Jul 13, 2015 at 10:54
  • Atm it loads and shows all tabs and all tabs content, but I'd like to show only active tab content.
    – DieZZzz
    Jul 13, 2015 at 11:03

1 Answer 1

2

Here is a basic idea as to how:

$(function() {

    $("#tabsId").on("click", "li", function(evt) {

        evt.preventDefault();
        var id = $(this).data("tabContent");
        $("#tabsContentId")
        .find(".tab-content[data-tab-content='" + id + "']").show()
        .siblings().hide();
    });
});

Take a look at this demo for a full example.

1
  • That's exactly what i was looking all day!
    – DieZZzz
    Jul 13, 2015 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.