'localStorage Remember Last Tab State

There are loads of exmaple of saving tab state with jQuery but not with Vanilla JS - I want to remember last tab state in the event a user leaves and returns to page, refreshes page etc. Would it be better to a sessions variable or is localstorage the best option ?

 <html>
 <head>
 <meta charset="utf-8">
<style>
    .red {
        background:red;
        color:#fff;
    }
    
    </style>
</head>

<body>
                <div class="container">
                    <div class="bar blue">
                            <button class="bar-item button tablink red" onclick="openTab(event,'Summary')">Summary</button>
                            <button class="bar-item button tablink" onclick="openTab(event,'Finance')">Finance</button>
                            <button class="bar-item button tablink" onclick="openTab(event,'Enquire')">Enquire</button>
                        <button class="bar-item button tablink" onclick="openTab(event,'Save')">Save</button>
                    </div>
                    <div id="Summary" class="container border vehTab">
                       FIRST TAB
                    </div>
                    <div id="Finance" class="container border vehTab" style="display:none">
                      SECOND TAB
                    </div>
                    <div id="Enquire" class="container border vehTab" style="display:none">
                      THIRD TAB                     
                        </div>
                        <div id="Save" class="container border vehTab" style="display:none">                                            
                      FOURTH TAB
                    </div>
        </div>
 <script>
 function openTab(evt, tabName) {
     var i, x, tablinks;
     x = document.getElementsByClassName("vehTab");
     for (i = 0; i < x.length; i++) {
         x[i].style.display = "none";
     }
     tablinks = document.getElementsByClassName("tablink");
     for (i = 0; i < x.length; i++) {
         tablinks[i].className = tablinks[i].className.replace("red", "");
     }
     document.getElementById(tabName).style.display = "block";
     evt.currentTarget.className += " red";
  }
    </script> 
   </body>
 </html>


Solution 1:[1]

Sessions are destroyed once the user closes the tab or browser. I would suggest localstorage over session storage in your case

Solution 2:[2]

Storing in session will be destroyed when the user closes the tab or browser.

Storing in local storage will be present for up to a lifetime until you clear it. If you are using local storage in secured pages (logged in user only has access to it) I suggest that it should be cleared when the user loges out

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sathya
Solution 2 Udhayakumar