0

I want to create a link that will target a specific tab, in another page of my site.

I have tried to create link like this: www.example.com/test.html#tab2, but it always targets the first tab (I guess the tab with show class).

index.html

<a href="test.html#menu-catalog">link for catalog</a>

text.html

<ul class="nav nav-tabs">
  <li id="homeTab" class="active"><a data-toggle="tab" href="#home" aria-expanded="true">menu 1</a></li>
  <li id="menu1Tab"><a data-toggle="tab" href="#menu1">menu 2</a></li>
  <li id="menu2Tab"><a data-toggle="tab" href="#menu-catalog">menu 3</a></li>
  <li id="menu3Tab"><a data-toggle="tab" href="#menu3">menu 4</a></li>
</ul>

<div class="tab-content">
  <div id="home" class="tab-pane fade in active">  
    ...
  </div>
  <div id="menu1" class="tab-pane fade">
   ....
  </div>
  <div id="menu-catalog" class="tab-pane fade">
    ...
  </div>
  <div id="menu3" class="tab-pane fade">
    ...
  </div>
</div>

When I click the link from index.html to target and open the tab with the right ID.

Alok Mali
  • 2,821
  • 2
  • 16
  • 32
Aggz
  • 31
  • 1
  • 1
  • 3
  • See here :) [https://stackoverflow.com/questions/48518237/how-to-open-a-tab-from-external-link/48520606](https://stackoverflow.com/questions/48518237/how-to-open-a-tab-from-external-link/48520606) – Pavlishin Nikita Aug 26 '19 at 13:02
  • you're using the jquery + bootstrap setup? – Jhecht Mar 11 '20 at 19:16

2 Answers2

3

If you're using the bootstrap + jquery setup, you can get this behavior pretty easily with the following:

$(() => {
  const {
    hash
  } = document.location;
  if (!hash) return false;
  $(`.nav.nav-tabs [href="${hash}"]`).tab('show');
});
Jhecht
  • 4,407
  • 1
  • 26
  • 44
0

Try this

$(function(){
  var hash = window.location.hash;
  hash && $('ul.nav a[href="' + hash + '"]').tab('show');

  $('.nav-tabs a').click(function (e) {
    $(this).tab('show');
    var scrollmem = $('body').scrollTop();
    window.location.hash = this.hash;
    $('html,body').scrollTop(scrollmem);
  });
});
Darshit Hedpara
  • 660
  • 6
  • 17