Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How load to show a Bootstrap Tab on page load without flickering the first tab first?

I have a navbar that looks like this:

<ul class="nav navbar-nav">
    <li class="active">
        <a href="#personal" data-toggle="tab">Personal Info</a>
    </li>
    <li>
        <a href="#con-sib" data-toggle="tab">Contacts/Siblings</a>
    </li>
    <li>
        <a href="#state-fed" data-toggle="tab">State/Federal</a>
    </li>
    <li>
        <a href="#eth" data-toggle="tab">Ethnicity</a>
    </li>
    <li>
        <a href="#placement" data-toggle="tab">Placement</a>
    </li>
    <li>
        <a href="#medical" data-toggle="tab">Medical</a>
    </li>
    <li>
        <a href="#sch-release" data-toggle="tab">School Release</a>
    </li>
</ul>

I have some javascript code that sets the correct active tab:

$(document).ready(function() {
    var hash = window.location.hash;

    if (hash) {
        var selectedTab = $('.nav li a[href="' + hash + '"]');
        selectedTab.trigger('click', true);
        }
    });

The above code works well (ignore the second parameter to .trigger() -- it's used elsewhere in my application), but with one caveat. When the page loads, the first tab is loaded and then correct tab is quickly displayed after that.

How can I prevent the first tab from getting displayed before the correct tab is displayed?

like image 589
Nathan Jones Avatar asked Mar 20 '14 15:03

Nathan Jones


2 Answers

You can hide the class active which is the first tab on page load:

$(document).ready(function () {
    $('.active').hide();
    var hash = window.location.hash;

    if (hash) {
        var selectedTab = $('.nav li a[href="' + hash + '"]');
        selectedTab.trigger('click', true);
    }
});
like image 195
Felix Avatar answered Nov 07 '22 05:11

Felix


Rather than waiting for ready() to fire, try putting your code into an IIFE and placing it right before the closing </body> tag (and after the jQuery and Bootstrap <script> elements it depends upon).

    <script src="jquery.min.js"></script>
    <script src="bootstrap.min.js"></script>
    <script>
    (function(){
        // your code here
    })();
    </script>
</body>

This way it'll fire as soon as the document has finished parsing.

like image 1
Olly Hodgson Avatar answered Nov 07 '22 04:11

Olly Hodgson