javascript - Load tab content onclick with ajax -


i trying learn js , js templating libraries, i've difficulties using them. i'm trying build page load dynamically content json file using ajax , create tabs content.

json file structure

"id": "0",   "name": "some title", "content": "<h1>hello</h1>" 

here 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 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 load tab content onclick?

here basic idea 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 look @ demo full example.


Comments