1lnxba
Last Updated: September 19, 2016
·
31.27K
· mborn319
6c4b91c7e84c7f7915ecfa9468ac2362 normal

Load Bootstrap tabs dynamically

Need Bootstrap tabs, but with dynamic content? Use this JS to fetch the content before showing the tab. Works for in-content links as well.

Javascript

//the reason for the odd-looking selector is to listen for the click event
// on links that don't even exist yet - i.e. are loaded from the server.
$('#tabs').on('click','.tablink,#prodTabs a',function (e) {
    e.preventDefault();
    var url = $(this).attr("data-url");

    if (typeof url !== "undefined") {
        var pane = $(this), href = this.hash;

        // ajax load from data-url
        $(href).load(url,function(result){      
            pane.tab('show');
        });
    } else {
        $(this).tab('show');
    }
});

Use a .tablink class on your in-content links to link between tabs. See comment in JS.

HTML

<div id="tabs">
    <ul class="nav nav-tabs" id="prodTabs">
        <li class="active"><a href="#tab_basic">Basic</a></li>
        <li><a href="#tab_images" data-url="?action=images">Images</a></li>
        <li><a href="#tab_videos" data-url="?action=videos">Videos</a></li>
    </ul>
    <div class="tab-content">
        <div id="tab_basic" class="tab-pane active"></div>
        <div id="tab_images" class="tab-pane active"></div>
        <div id="tab_videos" class="tab-pane active"></div>
    </div>
</div>

Adapted from: http://www.bootply.com/63891

Say Thanks
Respond

1 Response
Add your response

28151

Default on page load show tab code...
$('#tab-id').load('url', function (result) {
$('#tab-id').tab('show');
});

9 months ago ·