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

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 ?

This question is related to javascript jquery html css twitter-bootstrap

The answer is


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>

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;
    }); 
} 

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');
      };

Hi Try this one folks!

_x000D_
_x000D_
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {_x000D_
  // save current clicked tab in local storage does not work in Stacksnippets_x000D_
  // localStorage.setItem('lastActiveTab', $(this).attr('href'));_x000D_
});_x000D_
//get last active tab from local storage_x000D_
var lastTab = "#profile"; // localStorage.getItem('lastActiveTab');_x000D_
console.log(lastTab + "tab was last active")_x000D_
if (lastTab) {_x000D_
  $('[href="' + lastTab + '"]').tab('show');_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <div>_x000D_
    <!-- Nav tabs -->_x000D_
    <ul class="nav nav-tabs" role="tablist">_x000D_
      <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>_x000D_
      <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>_x000D_
      <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>_x000D_
      <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>_x000D_
    </ul>_x000D_
_x000D_
    <!-- Tab panes -->_x000D_
    <div class="tab-content">_x000D_
      <div role="tabpanel" class="tab-pane active" id="home">Home</div>_x000D_
      <div role="tabpanel" class="tab-pane" id="profile">Profile</div>_x000D_
      <div role="tabpanel" class="tab-pane" id="messages">Message</div>_x000D_
      <div role="tabpanel" class="tab-pane" id="settings">Settings</div>_x000D_
    </div>_x000D_
_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


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


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')
})

    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');
    }

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>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation