AJAX Tabs in Bootstrap 2.1

Note: When this article was written, the code was tested against Bootstrap v2.1.1 and jQuery v1.8.1 although as it is very simple it should work on the latest versions.

I'm using Twitter Bootstrap in a new project and want to have the content of tabs dynamically loaded via AJAX.  Although in previous projects I have used  jQueryUI to achieve this I wanted to keep the look of all the user interface elements consistent throughout. As a result, I whipped up a simple piece of jQuery to do this and thought I'd share it in case it's useful to others.

First, we need to output the HTML markup to get Twitter Bootstrap to display the tabs correctly on the page. We do this with a simple <ul> construct, shown below:

<ul id="MainTabs" class="nav nav-tabs">
  <li><a data-target="#apple" data-toggle="tab" href="/apple.html">apple</a></li>
  <li><a data-target="#banana" data-toggle="tab" href="/banana.html">banana</a></li>
  <li><a data-target="#cherry" data-toggle="tab" href="/cherry.html">cherry</a></li>
</ul>

<div class="tab-content">
  <div class="tab-pane" id="apple">Loading...</div>
  <div class="tab-pane" id="banana">Loading...</div>
  <div class="tab-pane" id="cherry">Loading...</div>
</div>

Things to note:

  • We have given our <ul> construct an id of MainTabs. If you want to change this, make sure you also change the references to it in the jQuery code below.
  • Each <li> item contains a data-target attribute which corresponds to a <div> in the second section of code (which is where the content loaded via AJAX will be placed).
  • Each <li> item contains an href attribute which specifies the URL the AJAX call will use to fetch the content. This can be any URL (such as a PHP script) and can contain parameters as normal.

Now all we need to do is output some jQuery code to ensure that the content is loaded whenever the user clicks on a tab:

$(function() {
  $("#MainTabs").tab();
  $("#MainTabs").bind("show", function(e) {    
    var contentID  = $(e.target).attr("data-target");
    var contentURL = $(e.target).attr("href");
    if (typeof(contentURL) != 'undefined')
      $(contentID).load(contentURL, function(){ $("#MainTabs").tab(); });
    else
      $(contentID).tab('show');
  });
  $('#MainTabs a:first').tab("show");
});

We check to see if the "data-target" attribute is set before loading the content. This allows us to mix pre-populated tabs (specified in-line in the page HTML) with dynamic tabs which are loaded via AJAX.

Line 11 uses a:first to ensure that the first tab is selected when the page is initially loaded. If you need to select a different tab on page load (perhaps you are generating the markup from within a PHP script) then you can replace a:first with a[data-target="#apple"] where apple is the id of the tab you want selected.