Webbserver - Love Blomberg

Show sourcecode

The following files exists in this folder. Click to view.

public_html/gamla-kurser/js/

tabs.js

tabs.js

45 lines ASCII Windows (CRLF)
function openTab(evt, tabName) {
  // Declare all variables
  let i, tabcontent, tablinks;

  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
      tabcontent[i].style.display = "none";
  }

  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
      tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the button that opened the tab
  document.getElementById(tabName).style.display = "block";
  evt.currentTarget.className += " active";

  // Store the current tab in local storage
  localStorage.setItem("currentTab", tabName);
}

// Load the last active tab on page load
document.addEventListener("DOMContentLoaded", function() {
  let lastActiveTab = localStorage.getItem("currentTab");
  if (lastActiveTab) {
      let tabButton = document.querySelector('.tablinks[id="' + lastActiveTab + '"]');
      if (tabButton) {
          tabButton.click(); // Trigger a click event on the tab button
      }
  }
});
// Save the active tab in local storage before the page is unloaded
window.addEventListener("beforeunload", function() {
  let activeTab = document.querySelector(".tablinks.active");
  if (activeTab) {
    localStorage.setItem("currentTab", activeTab.id);
  }
});
if (lastActiveTab) {
  openTab(event, lastActiveTab);
}