How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

JavascriptJqueryHtmlCssTwitter Bootstrap

Javascript Problem Overview


I am new to jquery and bootstrap,so please consider my mistakes.I have created a bootstrap modal for login and registration. It contains two nav-tabs called as login and registration.I have two buttons that popup the same Modal window, but display a different tab inside the Modal window. In each tab is a form with a number of inputs. My issue is getting the modal popped up with login tab opened in the modal when i click on the 'login' button and registration tab opened when i click on the 'register' button on my page.

These are 2 links on which the modal opens:

<div class="header-login-li" style="background-color:gray;float:left;width:100px;height:60px;">
<a data-toggle="modal" href="#regestration" class="header-register-a" >
<big>
<font color="white" class="header-register-font"><center style="margin-top:20px;">Login <i class="icon-chevron-down" style="font-size:20px"></i></center></font>
</big></a></div>

<div class="header-register-li" style="background-color:green;float:right;margin-right:-15px;width:130px;height:60px;">
<a data-toggle="modal" href="#regestration" class="header-register-a" >
<big>
<font color="white" class="header-register-font"><center style="margin-top:20px;">Register</center></font>
</big></a>

Here is my code of tabs and their contents(i am avoiding unnecessary code here):

 <div class="tabbable" >
      <ul class="nav nav-tabs" ><!--tabs-->
        <li class="active" style="position:absolute;margin-left:0px;" id="logintab">
        <a href="#pane_login" data-toggle="tab">Login</a></li>
        <li style="margin-left:70px;" id="reg_tab" ><a href="#pane_reg" data-toggle="tab">Registration</a></li>
        
      </ul>
      <div class="tab-content"><!--login tab content-->
         <div id="pane_login" class="tab-pane active">
             <form id="login-form" target="login-signup-iframe" method="post" action="#" name="login-form">
                    
              </form>
            
        </div><!--/pane_login-->
        
        <div id="pane_reg" class="tab-pane"><!--registration tab content-->
           <form id="regestration-form" target="login-signup-iframe" method="post" action="#" name="regestration-form">
                
            </form>
         </div>
        </div><!-- /.tab-content -->
</div><!-- /.tabbable -->

I think this can be done through jquery easily.But i dont know exactly how to do it. So,please can anyone help me to solve my problem.Thank you in advance ?

Javascript Solutions


Solution 1 - Javascript

Applying a selector from the .nav-tabs seems to be working

HTML is

<ul class="nav nav-tabs">
    <li><a href="#aaa" data-toggle="tab">AAA</a></li>
    <li><a href="#bbb" data-toggle="tab">BBB</a></li>
    <li><a href="#ccc" data-toggle="tab">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
    <div class="tab-pane" id="aaa">...Content...</div>
    <div class="tab-pane" id="bbb">...Content...</div>
    <div class="tab-pane" id="ccc">...Content...</div>
</div>

Script is

$(document).ready(function(){
  activaTab('aaa');
});

function activaTab(tab){
  $('.nav-tabs a[href="#' + tab + '"]').tab('show');
};


http://jsfiddle.net/pThn6/80/

Solution 2 - Javascript

HTML:

<a href="PageName.php#tabID">link to other page tab</a>

Javascript:

window.onload = function(){  

	var url = document.location.toString();
	if (url.match('#')) {
		$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
	}

	//Change hash for page-reload
	$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').on('shown', function (e) {
		window.location.hash = e.target.hash;
	}); 
} 

Solution 3 - Javascript

You may access through tab Id as well, But that id is unique for same page. Here is an example for same

$('#product_detail').tab('show');

In above example #product_details is nav tab id

Solution 4 - Javascript

Hi Try this one folks!

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
  // save current clicked tab in local storage does not work in Stacksnippets
  // localStorage.setItem('lastActiveTab', $(this).attr('href'));
});
//get last active tab from local storage
var lastTab = "#profile"; // localStorage.getItem('lastActiveTab');
console.log(lastTab + "tab was last active")
if (lastTab) {
  $('[href="' + lastTab + '"]').tab('show');
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<div class="container">
  <div>
    <!-- Nav tabs -->
    <ul class="nav nav-tabs" role="tablist">
      <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>
      <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
      <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
      <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>
    </ul>

    <!-- Tab panes -->
    <div class="tab-content">
      <div role="tabpanel" class="tab-pane active" id="home">Home</div>
      <div role="tabpanel" class="tab-pane" id="profile">Profile</div>
      <div role="tabpanel" class="tab-pane" id="messages">Message</div>
      <div role="tabpanel" class="tab-pane" id="settings">Settings</div>
    </div>

  </div>
</div>

Solution 5 - Javascript

Thanks for above answer , here is my jQuery code that is working now:

      $(".header-login-li").click(function(){
        activaTab('pane_login');                
      });
      
      $(".header-register-li").click(function(){
        activaTab('pane_reg');
        $("#reg_log_modal_header_text").css()
      });
      
      function activaTab(tab){
        $('.nav-tabs a[href="#' + tab + '"]').tab('show');
      };

Solution 6 - Javascript

	function updateURL(url_params) {
		if (history.pushState) {
		var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + url_params;
		window.history.replaceState({path:newurl},'',newurl);
		}
	}

	function setActiveTab(tab) {
		$('.nav-tabs li').removeClass('active');
		$('.tab-content .tab-pane').removeClass('active');

		$('a[href="#tab-' + tab + '"]').closest('li').addClass('active');
		$('#tab-' + tab).addClass('active');
	}

	// Set active tab
	$url_params = new URLSearchParams(window.location.search);


	// Get active tab and remember it
	$('a[data-toggle="tab"]')
		.on('click', function() {
		$href = $(this).attr('href')
		$active_tab = $href.replace('#tab-', '');

		$url_params.set('tab', $active_tab);
		updateURL($url_params.toString());
	});

	if ($url_params.has('tab')) {
		$tab = $url_params.get('tab');
		$tab = '#tab-' + $tab;
		$myTab = JSON.stringify($tab);
		$thisTab = $('.nav-tabs a[href=' + $myTab  +']');
		$('.nav-tabs a[href=' + $myTab  +']').tab('show');
	}

Solution 7 - Javascript

May I suggest a php+css solution I used on my site? It's simple and no js problems :)

url to page: <a href="page.php?tab=menu1">link to menu1</a>

<?
$tab = $_GET['tab'];
?>
<ul class="nav nav-tabs">
  <li class="<? if ($tab=='menu1' OR $tab=='menu2') 
{
echo "";
} 
else {
echo "active";
}
?>"><a data-toggle="tab" href="#home">Prodotti</a></li>
  <li class="<? if ($tab=='menu1') 
{
echo "active";
} 
?>"><a data-toggle="tab" href="#menu1">News</a></li>
  <li class="<? if ($tab=='menu2') 
{
echo "active";
} 
?>"><a data-toggle="tab" href="#menu2">Gallery</a></li>
</ul>

<div class="tab-content">
  <div id="home" class="tab-pane fade <? if ($tab=='menu1' OR $tab=='menu2') 
{
echo "";
} 
else {
echo "in active";
}
?>
">
    <h3>Prodotti</h3>
    <p>Contenuto della pagina, zona prodotti</p>
  </div>
  <div id="menu1" class="tab-pane fade <? if ($tab=='menu1') 
{
echo "in active";
} 
?>">
    <h3>News</h3>
    <p>Qui ci saranno le news.</p>
  </div>
  <div id="menu2" class="tab-pane fade <? if ($tab=='menu2') 
{
echo "in active";
} 
?>">
    <h3>Gallery</h3>
    <p>Qui ci sarĂ  la gallery</p>
  </div>
</div>

Solution 8 - Javascript

I wrote this snippet, that I've been using for handling this exact case.

It's in plain javascript, making it also suitable in cases like with bootsrap5 without jQuery.

<script type='text/javascript'>
	window.onhashchange=hashTriggerTab;
	window.onload=hashTriggerTab;
	
	function hashTriggerTab(){
		var current_hash=window.location.hash;
		if(current_hash.substring(0,1)=='#')current_hash=current_hash.substring(1);
		if(current_hash!=''){
			var trigger=document.querySelector('.nav-tabs a[href="#'+current_hash+'"]');
			if(trigger)trigger.click();
		}
	}
</script>

With that in place, you could link both on the same page, like:

<a href='#tabId'>Link Any Tab</a>

Or from external page like:

<a href='newpage.php#tabId'>Link From External</a>

Solution 9 - Javascript

Not sure if I understood correctly but here is snippet that I use to open links from Bootstrap tab menu:

HTML

<ul class="nav nav-tabs">
  <li class="active"><a href="#foo" data-toggle="tab">Foo</a></li>
  <li><a href="#bar" data-toggle="tab">Bar</a></li>
  <li><a href="baz.html" class="external">Baz</a></li>
</ul>

<div class="tab-content">
  <div class="tab-pane active" id="foo">Foo</div>
  <div class="tab-pane" id="bar">Bar</div>
</div>

Javascript

$('.nav a:not(".external")').click(function (e) {
  e.preventDefault()
  $(this).tab('show')
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsachin_wareView Question on Stackoverflow
Solution 1 - JavascriptSridhar RView Answer on Stackoverflow
Solution 2 - JavascriptRachView Answer on Stackoverflow
Solution 3 - JavascriptNikunj K.View Answer on Stackoverflow
Solution 4 - JavascriptJoempossibleView Answer on Stackoverflow
Solution 5 - Javascriptsachin_wareView Answer on Stackoverflow
Solution 6 - JavascriptZachary HeatonView Answer on Stackoverflow
Solution 7 - JavascriptLaura GargiuloView Answer on Stackoverflow
Solution 8 - JavascripttormutoView Answer on Stackoverflow
Solution 9 - JavascriptMars RobertsonView Answer on Stackoverflow