csstoggledarkmodescrypt

Darkmode toggle - two buttons - only one works


I am new here and hope you can help me :) Basically I have created a script that detects the darkmode of the browser and displays the web page accordingly.

In addition, it should be possible to switch between light and dark mode with the help of a button. The whole thing works great, but I want to integrate this button in two places on my website. But only one of them works.

Probably it is because of the "const" attributes in the script. However, I don't know what I have to change.

does anyone of you have an idea? Attached is a jsfiddle that shows the problem: https://jsfiddle.net/ubL63k0g/

JS:

const btn = document.querySelector(".btn-toggle-darkmode");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");

const currentTheme = localStorage.getItem("theme");
if (currentTheme == "dark") {
  document.body.classList.toggle("dark-theme");
} else if (currentTheme == "light") {
  document.body.classList.toggle("light-theme");
}

btn.addEventListener("click", function() {
  if (prefersDarkScheme.matches) {
    document.body.classList.toggle("light-theme");
    var theme = document.body.classList.contains("light-theme") ?
      "light" :
      "dark";
  } else {
    document.body.classList.toggle("dark-theme");
    var theme = document.body.classList.contains("dark-theme") ?
      "light" :
      "dark";
  }
  localStorage.setItem("theme", theme);
});

Thanks a lot to all of you!


Solution

  • this is because you using document.querySelector(".btn-toggle-darkmode"); this will get one element, so it only listen for one. You must use document.querySelectorAll(".btn-toggle-darkmode");

    const btns = document.querySelectorAll(".btn-toggle-darkmode");
    const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
    
    const currentTheme = localStorage.getItem("theme");
    if (currentTheme == "dark") {
    console.log(currentTheme)
      document.body.classList.toggle("dark-theme");
    } else if (currentTheme == "light") {
      document.body.classList.toggle("light-theme");
    }
    
    btns.forEach(function(btn){
    btn.addEventListener("click", function() {
      if (prefersDarkScheme.matches) {
        document.body.classList.toggle("light-theme");
        var theme = document.body.classList.contains("light-theme") ?
          "light" :
          "dark";
      } else {
        document.body.classList.toggle("dark-theme");
        var theme = document.body.classList.contains("dark-theme") ?
          "light" :
          "dark";
      }
      localStorage.setItem("theme", theme);
    });
    })