Search code examples
jqueryajaxjquery-uijquery-ui-tabsjquery-tabs

jQuery UI tabs with Ajax-based content: how to avoid first panel loaded by AJAX call


Suppose to use jQuery UI tabs and to load tabs content by means of an AJAX call, e.g.:

<div id="tabbed-menu">
    <ul>
        <li><a href="url1">LINK1</a></li>
        <li><a href="url2">LINK2</a></li>
        <li><a href="url3">LINK3</a></li>
    </ul>
</div>  

with the following Javascript code:

$(function() {
  $("#tabbed-menu").tabs();
});

Now, on document.ready the tabbed menu is created and the content of the first tab is loaded by a server request.

Suppose I want to replace this additional unnecessary server request. For instance, I can load the page with the whole content of the first tab.

How con I solve this issue?


Solution

  • You can provide an id selector instead of an URL in the href attribute of the first tab. For instance:

    <div id="tabbed-menu">
        <ul>
            <li><a href="#content1">LINK1</a></li>
            <li><a href="url2">LINK2</a></li>
            <li><a href="url3">LINK3</a></li>
        </ul>
        <div id="content1">
            Content of first tab.
        </div>
    </div>
    

    Moreover, if you want to let the first tab to be reloaded in a second time, you can: 1) add the url of the new content to the anchor, e.g.:

    <a href="#content1" data-url="url1">LINK1</a>
    

    2) Bind the tabbselect event to intercept the static content loading to replace it with a content reload, e.g.:

    $("#private-area-menu").bind("tabsselect", function(event, ui) {
          if(ui.index==0){
              $('#tab-content').html(''); // required to clear the previous static data
              $('#tab-content').load($(ui.tab).attr('data-url')); // refresh data              
          }
    });