Home > OS >  stay in the same tab after refreshing page
stay in the same tab after refreshing page

Time:11-17

I have a page which contains same url but a lot of tabs after I click on a tab I can see its content but right after I refresh the page tab(0) appear but I want the last used tab. how can I do that. this is the js code

<script>
    const tabBtn = document.querySelectorAll(".tab");
    const tab = document.querySelectorAll(".tabShow");
    function tabs(panelIndex){
        tab.forEach(function(node){
            node.style.display="none";
        });
        tab[panelIndex].style.display="block";
    }
    tabs(0);
    $(".tab").click(function(){
        $(this).addClass("active").siblings().removeClass("active");
    });
</script>

CodePudding user response:

You can use Session Storage or Query parameters (search parameters) or Hash parameters

Session Storage: can store some values by keys until the tab is closed
Hash Parameters: data is stored in the url. You can even save the url somewhere or share it, and when it is open the required tab will be opened
Query Parameters: the same as Hash Parameters but when changed the whole page refreshes

Session Storage solution:

<script>
  const tabButtons = document.querySelectorAll(".tab");
  const tabs = document.querySelectorAll(".tabShow");

  const changeTab = (tabIndex) => {
    sessionStorage.setItem('currentTab', tabIndex);

    tabs.forEach((node) => { node.style.display = "none"; });
    tabButtons.forEach((tb) => tb.classList.remove('active'));

    tabs[tabIndex].style.display = "block";
    tabButtons[tabIndex].classList.add('active');
  }

  tabButtons.forEach((tabButton, index) => {
    tabButton.onclick = () => changeTab(index)
  });

  changeTab(sessionStorage.getItem('currentTab') || 0);
</script>

Hash Parameters solution:

<script>
  const tabButtons = document.querySelectorAll(".tab");
  const tabs = document.querySelectorAll(".tabShow");

  const changeTab = (tabIndex) => {
    window.location.hash=`tab=${tabIndex}`;

    tabs.forEach((node) => { node.style.display = "none"; });
    tabButtons.forEach((tb) => tb.classList.remove('active'));

    tabs[tabIndex].style.display = "block";
    tabButtons[tabIndex].classList.add('active');
  }

  tabButtons.forEach((tabButton, index) => {
    tabButton.onclick = () => changeTab(index)
  });

  const hash = new URLSearchParams(location.hash.slice(1));
  changeTab(hash.get('tab') || 0);
</script>

Query Parameters solution
The same as Hash Parameters solution, but with search instead of hash

CodePudding user response:

You could create a variable that is updated each time the tab is changed and then check what the variable is equal to to determine which tab should be opened by default.

  • Related