How to use AJAX loading with Bootstrap tabs?

In Bootstrap 2.0 and up you have to bind to the ‘show’ event instead.

Here’s an example HTML and JavaScript:

<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</li>
    </ul>
    <div>
        <div class="tab-pane active" id="home"></div>
        <div class="tab-pane" id="foo"></div>
        <div class="tab-pane" id="bar"></div>
    </div>
</div>

JavaScript:

$(function() {
    var baseURL = 'http://yourdomain.com/ajax/';
    //load content for first tab and initialize
    $('#home').load(baseURL+'home', function() {
        $('#myTab').tab(); //initialize tabs
    });    
    $('#myTab').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(){
            $('#myTab').tab(); //reinitialize tabs
       });
    });
});

I wrote a post about it here: http://www.mightywebdeveloper.com/coding/bootstrap-2-tabs-jquery-ajax-load-content/

Leave a Comment