DEV Community

andysaktia
andysaktia

Posted on • Edited on

Active Tab When Open with Url-Tab Shareable

In this case, in one page having bootstrap tabs, the problem arises when the user wants to share content based on the tabs has has opened (not the first tab which is usually the default).

Alt Text

Purpose

Open destination tab when open window with url

Prerequire

  • Bootstrap; js tab function
  • Jquery and javascript

Script

To activate the tab, first create an activeTab function with a known pattern name parameter. After that I just activate the function. Note: In this part important to understanding js tab in Bootstrap!

//<1>
    function activaTab(tab){
          let someTabTriggerEl = $('.nav-tabs button[data-bs-target="#nav-' + tab + '"]')
          let tab = new bootstrap.Tab(someTabTriggerEl)
          tab.show()
    };
Enter fullscreen mode Exit fullscreen mode

Before executing activeTab function, I need to fetch all tab items with jquery selector with class attribute tag-tab. The html tab item is as follows <span id="audio" class="tab-tag">Audio</span> , then performs a query with the condition that the id attribute is the same as tagUrl, which is obtained from the split url with the split attribute #, e.g. http:/website.org/page.php#audio.

//<2>
    // get URl
    let curentUrl = window.location.href;
    var tagUrl = curentUrl.split("#")[1];

    // query tab to active function <1>
    var arrTag = $('.tab-tag');
    if (typeof tagUrl !== "undefined") {
      arrTag.each(function(){
          let tagSpesific = ($(this).attr('id'));
          if (tagSpesific == tagUrl){ 
            activaTab(tagUrl);
          }
      });
    }

Enter fullscreen mode Exit fullscreen mode

Done

Top comments (0)