javascript - Twitter Bootstrap 5 Tabs: Go to Specific Tab on Page Reload or Hyperlink - Stack Overflow

How could you link to bootstrap 5 tabs directly as with previous bootstrap methods according to?:Twitt

How could you link to bootstrap 5 tabs directly as with previous bootstrap methods according to?:

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

I've tried the following approach:

var hash = location.hash.replace(/^#/, ""); // ^ means starting, meaning only match the first hash
if (hash) {
  var someTabTriggerEl = document.querySelector("#" + hash + "");
  var tab = new bootstrap.Tab(someTabTriggerEl);

  tab.show();
}

How could you link to bootstrap 5 tabs directly as with previous bootstrap methods according to?:

Twitter Bootstrap Tabs: Go to Specific Tab on Page Reload or Hyperlink

I've tried the following approach:

var hash = location.hash.replace(/^#/, ""); // ^ means starting, meaning only match the first hash
if (hash) {
  var someTabTriggerEl = document.querySelector("#" + hash + "");
  var tab = new bootstrap.Tab(someTabTriggerEl);

  tab.show();
}
Share Improve this question asked Oct 14, 2021 at 15:29 stacksterstackster 414 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Assuming the tab trigger is from a <ul> list, and the query string hash is the target in the href, then the Bootstrap 5 method for showing a tab when the page loads would be:

<ul class="nav nav-tabs">
  <li class="nav-item">
    <a class="nav-link" data-bs-toggle="tab" href="#someTarget">Some Target</a>
  </li>
</ul>
document.addEventListener("DOMContentLoaded", () => {
  const trigger = document.querySelector(`ul.nav a[href="${window.location.hash}"]`)
  const tab = new bootstrap.Tab(trigger)
  tab.show()
})

The above does not check for invalid query string hash names or valid dom elements; add as-needed.

Currently solved this with:

var hash = location.hash.replace(/^#/, "");
if (hash) {
  var triggerEl = document.querySelector("#" + hash + "-tab");
  triggerEl.click();
}

The Jquery solution:

$(function () {
    //---if hash is provided for tab, then open and focus that tab
    if (window.location.hash) {
        const tab_id = window.location.hash;

        const $tab = $(tab_id);
        if ($tab.length) {
            $tab.tab('show');
            $tab[0].scrollIntoView({ behavior: 'smooth' });
        }
    }
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745317239a4622274.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信