How to boot to show the Bootstrap tab on the page load without first blinking the first tab?

I have a navigation bar 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 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 .trigger() - it is used elsewhere in my application), but with one caveat. When the page loads, the first tab loads, and then the tab quickly displays after that.

How can I prevent the first tab from appearing until the correct tab is displayed?

+7
javascript jquery css twitter-bootstrap tabs
source share
2 answers

You can hide the active class, which is the first tab of the 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); } }); 
+8
source share

Instead of waiting for ready() to start, try putting your code in IIFE and placing it right before the closing </body> (and after jQuery and the Bootstrap <script> elements it depends on).

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

Thus, it will light up as soon as the document finishes parsing.

+1
source share

All Articles