简体   繁体   中英

How to save change state in javascript

While returning back from the link in the second tab ie from swiggy, it always redirecting to first tab

How can I save the state change?

<div class="tab">
  <button class="tablinks" onclick="openFood(event, 'Zomato')" id="defaultOpen">Zomato</button>
  <button class="tablinks" onclick="openFood(event, 'Swiggy')">Swiggy</button>
</div>

<div id="Zomato" class="tabcontent">
  <h3>Zomato</h3>
  <a href="https://www.zomato.com/kingman-ks">Zomato</a>
</div>

<div id="Swiggy" class="tabcontent">
  <h3>Swiggy</h3>
   <a href="https://www.swiggy.com/">Swiggy</a>
</div>
<script>
function openFood(evt, FoodVendor) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(FoodVendor).style.display = "block";
  evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</script>
   

Put simply, your JavaScript runs each time the page is refreshed; when a user clicks one of the links in the DOM (or what you've written between html tags), the script is run from top to bottom with no idea of what happened previously.

State management is a difficult but common problem in modern user interfaces, which is why we have JavaScript libraries like Angular , React , Vue , JQuery UI , and others to take care of the complex under-the-hood concerns and allow your UI's state to persist and your components to be reactive (ie a user clicks a tab and the active class is applied without a refresh).

If you need a super simple implementation that persists across refreshes you could:

  1. Use Local Storage or Session Storage to maintain the active tab, eg
window.localStorage.setItem('activeTab', 'Swiggy');
// after user refreshes
const id = window.localStorage.getItem('activeTab');
const el = document.getElementById(id);
el.className += "active";
// (you'll also have to remove the active class from the "default" active tab etc.)
  1. Use a query string , eg
// user navigates to https://yoursite.com/yourendpoint?activeTab=Swiggy
function checkForActiveTabQueryString() {
  const params = new URLSearchParams(window.location.search);
  const activeTab = params.get("activeTab");

  if (activeTab) {
    const el = document.getElementById(activeTab);
    if (el) {
      el.className += "active";
    }
    // you'll have to remove the active class from the "default" tab, 
    // etc.
  }
}

You can use HTML5 LocalStorage Object to save some parameter for the current tab locally in the browser and get it back to make the last active tab selected on page reload. Check this tutorial.

What I've changed (add/remove) :

  1. Remove DefaultOpen

    But instead I added ' active ' class to Zomato Button. And set display:none to tabcontent .

  2. Add Local Storage

    • Everytime the tab changes ie everytime openFood() is called, we save the currentState to localStorage with variable name activeTab (value is either 'Zomato' or 'Swiggy').

      localStorage.setItem('activeTab', FoodVendor);

    • When the page loads, we check activeTab value and decide which tab to open.

       $(document).ready(function(){ var activeTab = localStorage.getItem('activeTab'); if (activeTab == 'Swiggy'){ openFood('SwiggyTab', 'Swiggy'); } else if(activeTab == 'Zomato'){ openFood('ZomatoTab', 'Zomato'); } });

CSS

<style type="text/css">
    div.tabcontent{
        display: none;
    }
</style>

HTML

<div class="tab">
  <button class="tablinks active" id="ZomatoTab" onclick="openFood('ZomatoTab', 'Zomato')">Zomato</button>
  <button class="tablinks" id="SwiggyTab" onclick="openFood('SwiggyTab', 'Swiggy')">Swiggy</button>
</div>

<div id="Zomato" class="tabcontent">
  <h3>Zomato</h3>
  <a href="https://www.zomato.com/kingman-ks">Zomato</a>
</div>

<div id="Swiggy" class="tabcontent">
  <h3>Swiggy</h3>
   <a href="https://www.swiggy.com/">Swiggy</a>
</div>

JavaScript

<script type="text/javascript">
    $(document).ready(function(){
        //get activeTab from LocalStorage
        var activeTab = localStorage.getItem('activeTab');
        //Decide which tab to open
        if (activeTab == 'Swiggy'){
            openFood('SwiggyTab', 'Swiggy');
        }
        else{
            openFood('ZomatoTab', 'Zomato');
        }
    });
    function openFood(id, FoodVendor) {
      var i, tabcontent, tablinks;
      tabcontent = document.getElementsByClassName("tabcontent");
      for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
      }
      tablinks = document.getElementsByClassName("tablinks");
      for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
      }
      
      document.getElementById(FoodVendor).style.display = "block";
      document.getElementById(id).className += " active";
      
      //Save the latest activeTab
      localStorage.setItem('activeTab', FoodVendor);
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM