-1

I want to be able to send users a link that includes a hash that will open a specific tab on that link's page.

However, no matter which hash I place in the URL, that tab is never selected. Clicking the tab buttons work just fine, though.

How can I make a tab active simply by grabbing the hash from the URL?

This is my partial code:

<script>
$('.userhref').click(function(){
    $('#nav').find('li').find('a[href=' + $(this).attr('href') + ']').closest('li').addClass('active').siblings('li').removeClass('active');
});
</script>

<div class="tabbable nav-tabs-container" style="max-width:1000px;">
  <ul class="nav nav-tabs" id="nav" name="tabs" role="tablist">
    <li role="presentation"><a href="#tab1" aria-controls="tab1" role="tab" data-toggle="tab"> Description</a></li>
    <li role="presentation"><a href="#tab2" aria-controls="tab2" role="tab" data-toggle="tab"> Specs</a></li>
  </ul>
  <div class="tab-content">
    <div role="tabpanel" class="tab-pane" id="tab1">
      <h3>Tab 1</h3>
    </div>
    <div role="tabpanel" class="tab-pane" id="tab2">
      <h3>Tab 2</h3>
    </div>
  </div>
</div>

The full code and working example can be seen here:

https://www.s22.us/tabs.php#tab3

None of the solutions I've found work in this scenario.

Frank Jance
  • 115
  • 1
  • 9
  • 1
    [`:target`](//developer.mozilla.org/en/docs/Web/CSS/:target), [`hash`](//developer.mozilla.org/en/docs/Web/API/Location/hash), [How to read the #hash (or fragment identifier) of the current page URL?](/q/15741421/4642212). _“None of the solutions I've found work in this scenario.”_ — Please [edit] your question and provide a [mre]. – Sebastian Simon Jun 10 '23 at 18:34
  • What code are you using to read the fragment from the URL and set the active tab? You've only posted the HTML – Rory McCrossan Jun 10 '23 at 18:34
  • I also included a URL to a working copy. – Frank Jance Jun 10 '23 at 18:39

1 Answers1

1

You can select the appropriate tab based on location.hash and trigger a click on it on page load as well as the hashchange event.

function changeTab() {
    $(`a[role=tab][href='${location.hash}']`).click();
}
changeTab();
window.addEventListener('hashchange', changeTab);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80