Reft
Reft

Reputation: 2433

Bootstrap tabs - load ajax content first THEN switch tabs

I'm having troubles delaying the tab change when loading in content with ajax.

If I'm positioned in tab 0 and click on tab 1, I want the content to be loaded with ajax and when it's done, switch tab.

At the moment the tab is changed instant, which gives a blank side till my ajax content is loaded.

HTML:

<ul class="nav nav-tabs" id="tab" role="tablist">
    <li class="active"><a data-toggle="tab" id="tab1" href="#container1">Information</a></li>
    <li><a data-toggle="tab" id="tab2" href="#container2">Users</a></li>
</ul>

<div class="tab-content">
    @*TAB1*@
    <div class="tab-pane active" id="container1">
        @Html.Partial("_StaticContentFromView")
    </div>

    @*TAB2*@
    <div class="tab-pane" id="container2">
    </div>
</div>

JS:

$('#tab2').click(function () {
            $.ajax({
                url: '/Home/Test',
                type: 'GET',
                dataType: 'html',
                success: function (data) {
                    $('#container2').html(data);
                }
            });
        });

Update 1:

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
  e.target // activated tab
  e.relatedTarget // previous tab
})

This event fires before tab is changed, so I can probably load the content here. However this event is called everytime tab is changed. How can i check which tab is choosen? e.target gives me a url, that is not good enough..

Upvotes: 1

Views: 1877

Answers (1)

Reft
Reft

Reputation: 2433

Alright found a way..

$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
    var tabName = $(e.target).text(); //Get the name of the tab.

    if (tabName == 'Users') {
            $.ajax({
            url: '/Home/Test',
            type: 'GET',
            async: false,
            dataType: 'html',
            success: function (data) {
                $('#container2').html(data);
                e.target // activated tab
                e.relatedTarget // previous tab
            }
        });
    }
})

It's important that you set async to false otherwise it wont work.

Upvotes: 1

Related Questions