v2.5.2
Giriş yap

localStorage refresh

721eren
306 defa görüntülendi

javacsript karanlık / açık temayı tutmak için localStorage kullanıyorum fakat
kişi açık tema da refresh atarsa yine otomatik olarak dark-tema ya geçiyor

kısacası; açık temadaysa kişi refresh atınca açık tema da kalmaya devam etsin
fakat koyu temadaysa refresh atınca koyu modda olmaya devam etsin.

// change theme
themeToggler.addEventListener("click", () => {
  document.body.classList.toggle("dark-theme");
  if (document.body.classList != "dark-theme") {
    document.getElementById("btnChangeText").innerText = "Koyu Mod";
    document.getElementById("darkIcon").className = "fa-solid fa-moon";
  } else {
    document.getElementById("btnChangeText").innerText = "Açık Mod";



    localStorage.setItem('mode', document.body.classList);


    // eğer kişi açık tema da refresh atarsa
    // otomatik olarak dark temaya geri dönüyor, hallet onu
    document.getElementById("darkIcon").className = "fa-solid fa-sun";
  }
});

if (localStorage.getItem('mode') != '') {
  document.body.classList.add(localStorage.getItem('mode'));
  document.getElementById("btnChangeText").innerText = "Açık Mod";
}
else {
  localStorage.removeItem('dark-theme');
}
Cevap yaz
Cevaplar (2)
721eren
619 gün önce
(()=>{
  if(localStorage.getItem("mode")){
    const theme = localStorage.getItem('mode');
    const textElement =  document.getElementById("btnChangeText")
    const icon = document.getElementById("darkIcon")
    document.body.className= theme
    if(theme == "dark-theme"){
    textElement.innerText = "Açık Mod";
    icon.className = "fa-solid fa-sun";
   } 
   else if(theme == ""){
     textElement.innerText = "Koyu Mod";
     icon.className = "fa-solid fa-moon";
   }
  }
  })()
  
  // change theme
themeToggler.addEventListener("click", () => {
  document.body.classList.toggle("dark-theme");
  if (document.body.classList != "dark-theme") {
    document.getElementById("btnChangeText").innerText = "Koyu Mod";
    document.getElementById("darkIcon").className = "fa-solid fa-moon";
  } else {
    document.getElementById("btnChangeText").innerText = "Açık Mod";
    // eğer kişi açık tema da refresh atarsa
    // otomatik olarak dark temaya geri dönüyor, hallet onu
    document.getElementById("darkIcon").className = "fa-solid fa-sun";
  }
    localStorage.setItem('mode', document.body.classList);
});

buyrun bu işinizi görür. çalışıyor.

batuhanal
620 gün önce

Cookie kullanarak yap