Bootstrap 2.0 Tabs JQuery Ajax Example

In the project I’m currently working on we are moving from JQuery UI to a Twitter Bootstrap/JQuery approach. In JQuery UI it is very easy to setup your tabs so that content gets dynamically loaded. Getting the same functionality in Bootstrap requires a little bit of extra coding so here’s an example of how to load content into your Twitter Bootstrap tab elements using JQuery.  After some searching I found a couple of examples but they all seem to be built for earlier Bootstrap versions and won’t work for Bootstrap version 2.0 and up. This example is based on this post but has been updated to work with the latest version of Bootstrap (2.0.3 as of writing).

This example obviously requires JQuery and the Twitter Bootstrap Tabs plugin. Make sure you load both before the JavaScript snippet below.

Here’s the HTML for the tab elements.

 
<div class="tabbable">
    <ul class="nav nav-tabs" id="myTabs">    
        <li><a href="#home"  class="active" data-toggle="tab">Home</a></li>
        <li><a href="#foo" data-toggle="tab">Foo</a></li>
        <li><a href="#bar" data-toggle="tab">Bar</a></li>
    </ul>

    <div class="tab-content">
        <div class="tab-pane active" id="home"></div>
        <div class="tab-pane" id="foo"></div>
        <div class="tab-pane" id="bar">Some static text. (displayed if AJAX request fails)</div>
    </div>
</div>

As you can see we don’t specify any content for the default tab as we’ll load this using AJAX. In the code below the default content will be loaded from the URL http://yourdomain.com/ajax/home.

After the HTML add the following JavaScript to initialize the first tab with content and bind the dynamic loading of content to all tabs.

<script>
    $(function() {
        var baseURL = 'http://yourdomain.com/ajax/';
        //load content for first tab and initialize
        $('#home').load(baseURL+'home', function() {
            $('#myTabs').tab(); //initialize tabs
        });    
        $('#myTabs').bind('show', function(e) {    
           var pattern=/#.+/gi //use regex to get anchor(==selector)
           var contentID = e.target.toString().match(pattern)[0]; //get anchor         
           //load content for selected tab
            $(contentID).load(baseURL+contentID.replace('#',''), function(){
                $('#myTabs').tab(); //reinitialize tabs
            });
        });
    });
</script>

The event target contains the full URL including the anchor so we use a regex expression to grab the anchor (which equals #<id>, which equals the CSS selector!) value.

Now in order to load the content we append the id to create the Ajax URL’s so make sure the names of your Ajax handler functions correspond with these id’s. You can easily alter this and set up alternate logic to load other URL’s. Note that if the URL cannot be found the tab will display the static content that is defined in the corresponding div with class tab-pane.

Note that in pre-2.0 Bootstrap the function to initialize the tabs was called tabs() (plural) whereas in 2.0 and above it is just tab().

As always if you have any questions feel free to post in the comment section!

Leave a Reply

*

24 comments

  1. Ampac

    What coding logic would I use if I had a mix of tabs, some of which content was preloaded and others which used AJAX? With jquery UI it’s transparent but less so with bootstrap.

    In passing is there a particular reason that you adopted Bootstrap’s tab functionality over that of the jquery UI? Is there a downside to mixing various elements of jquery UI with Bootstrap?

    • admin

      Using the method described in the post it is also very easy to mix static and dynamic content. If the URL in the AJAX request does not exist the tab will simply show the HTML content of the corresponding tab-pane div. (I updated the example to include this, see the “Bar” tab). Alternatively you could add in some logic in the JavaScript to only perform a request when the id is within a specific list of values.

      The main reason for switching to Bootstrap in the first place was the great look and feel and the ease of use. Using the Bootstrap tabs was mainly to maintain a consistent look and feel and to keep things as lightweight as possible. There is no reason why you shouldn’t use JQuery UI in combination with Bootstrap however and there are lots of JQuery UI widgets that are not available in Bootstrap. If you need to use JQuery UI but want the Bootstrap styles maybe this port (3rd theme) of the Bootstrap styling to JQuery UI is for you.

  2. Luís Lopes

    $(‘#myads’)

    what’s this referring to?

    • admin

      Hi Luis, thanks for noting this error. I have updated the example.

  3. Nick

    Thank you, this really saved my @$$!

    I had a slightly different issue where my ajax was loading fine, but the DIV’s were being appenended, i.e, when I would click on a tab, the previous tab would be concated to the current one.

    I simply added the $(‘#tabs’).tabs() // reinitalize to my function

    function loader(url,target)
    {
    $(‘#’+target).html(“Loading…”);
    $(‘#’+target).load(url, function() {
    $(‘#nav_tabs’).tabs();
    });
    $(‘#’+target).addClass(‘fade’);

    return false;
    }

    Thanks!

  4. thanks

    Thanks but I also have the problem that the DIVS were being appended 🙁

    • edsel abucejo

      Have you solve your issue with the nav-tabs and tab-content are dynamically appended?

  5. Laurent Laville

    To solve the issue explained in previous comments, you ‘ll have to fix the hml code (line 10) and add attribute class=”tab-content” to the div element.

    All fine then for me !

    • admin

      Thanks Laurent! The div to be altered is on line 9, I have updated the example so it should be flawless now 😉

  6. RZT

    Rather than have the content fetched from a URL which relies on a specific naming format, I prefer to specify the source URLs in the tab definitions. This can be achieved in Bootstrap 2.0 by including both data-target and href attributes like so:


    <ul id="myTabs" class="nav nav-tabs" >
    <li><a data-target="#home" data-toggle="tab" href="/home.html">home</a></li>
    <li><a data-target="#foo" data-toggle="tab" href="/foo.html">foo</a></li>
    <li><a data-target="#bar" data-toggle="tab" href="/bar.html">bar</a></li>
    </ul>

    You can then modify the bind within the jQuery code as follows:


    $(function() {
    $("#myTabs").tab(); // initialize tabs
    $("#myTabs").bind("show", function(e) {
    var contentID = $(e.target).attr("data-target");
    var contentURL = $(e.target).attr("href");
    $(contentID).load(contentURL, function(){
    $("#myTabs").tab(); // reinitialize tabs
    });
    });
    $('#myTabs a:first').tab("show"); // Load and display content for first tab
    });

    • admin

      Elegant solution indeed, thanks!

    • The above is quite nice. I tweaked it a bit to only do ajax if href is present. If the href attribute wasn’t defined, then I show the static content… useful if 5 tabs are static, and one is dynamic.


      $("#myTabs").tab(); // initialize tabs
      $("#myTabs").bind("show", function(e) {
      var contentID = $(e.target).attr("data-target");
      var contentURL = $(e.target).attr("href");

      if (typeof(contentURL) != 'undefined') {
      // state: has a url to load from
      $(contentID).load(contentURL, function(){
      $("#myTabs").tab(); // reinitialize tabs
      });

      } else {
      //state: no url, to show static data
      $(contentID).tab('show');
      }
      });
      $('#myTabs a:first').tab("show"); // Load and display content for first tab

    • Kevin Bowersox

      I came to the same conclusion when working through this tutorial. After scanning the comments, I noticed someone else came up with this method. I prefer this approach.

  7. Mike Tommasi

    The closing is missing in the third tab…

    thx for the article, useful!

    • admin

      Updated the example, thanks!

  8. Thanks, It was a a great help. However do you have any example on how we can use html template and put dynamic content in tabs after loading them.

  9. Adam

    Hi,

    I have tested your code and it works perfect. Since Im new to JavaScript I need some help. I want to pass a variable to the php-page that is loaded. Need to get the id in the URL and then do a SQL-query in the PHP-page with the id.

    Do anyone now how to do this?

    Adam

  10. Edson Ferreira

    Great Article and this is exactly what I’m looking for!
    One (newbie) question: what would change if I was using a MVC controller to get my partial view to be injected into the tabs as they’re clicked ?

  11. Dylan

    This tutorial is great!
    I was wondering what the trick is for links in the body of a page?
    Obviously the navbar links well, but when trying to navigate to another nav-item from within the page, im having trouble figuring this out.
    Thanks!

    • edsel abucejo

      Wonderful article, I’m a newbie to jquery, I think this can help in my issues in my project. I tried the code above and its working fine, I want to do some tweak on it, in my code it will dynamically add a nav tab element and it’s corresponding tab-content element. how can I make use of the code above to make it load the tab content including the dynamically appended in nav-tab and tab-content? Hope you can help me with this issue.

Next ArticleFree SEO Tools