ALUW
ALUW

Reputation: 397

JavaScript keep tab on page reload

I have tabbed content that looks like this:

<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>

<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p> 
</div>

<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

And JavaScript for the tabs that looks like this:

<script>
function openCity(evt, cityName) {
    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(cityName).style.display = "block";
    evt.currentTarget.className += " active";
}

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

I'm using the code from W3 schools. When the page is reloaded I want the tab that I am on to stay not for it to reload to the default tab. EDIT: For clarification, I want the last tab I clicked to load when I refresh the page.

Upvotes: 0

Views: 297

Answers (2)

Jesse de gans
Jesse de gans

Reputation: 1654

I prefer using hashtags in the url.

You should change your buttont to <a> like so:

   <a class="tablinks" href="#london" onclick="openCity(event, 'London')">London</a>

Then on document ready check for hashtag and select the desired tab:

$( document ).ready(function() {
    if(window.location.hash == ""){
      openCity(event, 'London')
    } else if( window.location.hash == "#paris"{
      openCity(event, 'Paris')
    }
});

etc

Upvotes: 1

Matvey Andreyev
Matvey Andreyev

Reputation: 1061

You have to use some persistent storage method to achieve this: cookies or localStorage.

You have to save the name of a clicked tab inside your openCity function and read it near your click on id="defaultOpen". If no value has been read from cookie or localStorage, perform your default click.

I recommend PPK's cookie functions.

Upvotes: 1

Related Questions