Search code examples
javascripthtmlcookiestranslationmacos-darkmode

How to use cookies to run "oneClick"


My website has two main features: first it supports the dark mode with/and without macOS/iOS (there is a toggle on the website) and I use different tabs with javascript as translations of the website. Now I want to have the function, to save/get a cookie which first saves whether the dark mode was toggled manually and saves which language was the last clicked, because when you come to a new page, the dark mode should be on or off and just this last chosen language should appear.

I already tried the genreal get/save-functions for cookies in javascript, but I don't know how to apply these to my code exactly.

That's my actual script.js without the cookie-functions:

function openCity(evt, langName) {
  // Declare all variables
  var 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(langName).style.display = "block";
  evt.currentTarget.className += " active";
}

  document.getElementById("index").click();

//Darkmode

  $('#mode').change(function(){

    var os2 = new Audio('../images/os2.mp3');
    var dmmodus = new Boolean([false])

      if ($(this).prop('checked'))
      {
          $('body').addClass('dark-mode');
          os2.play();
      }
      else
      {
          $('body').removeClass('dark-mode');
      }

  });


  //kontakt
  document.getElementById('options').onchange = function() {
  var i = 1;

  var myDiv = document.getElementById(i);
  while (myDiv) {
    myDiv.style.display = 'none';
    myDiv = document.getElementById(++i);
  }
  document.getElementById(this.value).style.display = 'block';
};

Solution

  • Use localStorage instead. Cookies are only needed if you need to communicate the settings to the backend

    Try this

    $('#mode').on("change",function() {
      var darkMode = $(this).prop('checked');
      localStorage.setItem("mode",darkMode?"dark":"") 
      $('body').toggleClass('dark-mode',darkMode);
      if (darkMode) {
        new Audio('../images/os2.mp3').play();
      }
    }).prop("checked",localStorage.getItem("mode") == "dark")
      .change(); // initialise from localStorage