简体   繁体   中英

Setting up a dark mode toggle button dynamically with vanilla JS

I am trying to add a dark/light mode toggle button dynamically through JS to implement on all my WordPress pages. However, I am getting an error when it comes to the toggleSwitch variable, which is undefined and I'm unsure as to why at this point. Any leads are greatly appreciated!

function lightDarkMode() {

  const themeSwitch = document.createElement("label");
  themeSwitch.type = "checkbox";
  themeSwitch.classList.add("theme-switch");

  themeSwitch.innerHTML = `<input type="checkbox" id="checkbox" />
    <div class="slider round"></div>`;

  const em = document.createElement("em");
  em.innerHTML = "Enable Dark Mode!";

  const toggleSwitch = document.querySelector(
    '.theme-switch input[type="checkbox"]'
  );
  const currentTheme = localStorage.getItem("theme");

  if (currentTheme) {
    document.documentElement.setAttribute("data-theme", currentTheme);

    if (currentTheme === "dark") {
      toggleSwitch.checked = true;
    }
  }

  function switchTheme(e) {
    if (e.target.checked) {
      document.documentElement.setAttribute("data-theme", "dark");
      localStorage.setItem("theme", "dark");
    } else {
      document.documentElement.setAttribute("data-theme", "light");
      localStorage.setItem("theme", "light");
    }
  }

  toggleSwitch.addEventListener("change", switchTheme, false);
}

The problem here is that you have created an element dynamically using javascript that is not present in the DOM. And you are querying that element using querySelector for the element which is not present in the document. So, in order to make it work, you need to add the created element in the DOM as well. You can use.append method.

You can do something like this: -

  const themeSwitch = document.createElement("label");
  themeSwitch.type = "checkbox";
  themeSwitch.classList.add("theme-switch");

  themeSwitch.innerHTML = `<input type="checkbox" id="checkbox" />
    <div class="slider round"></div>`;

  const em = document.createElement("em");
  em.innerHTML = "Enable Dark Mode!";

  //append the created element so that you can fetch it using query
  document.body.append(themeSwitch);

  const toggleSwitch = document.querySelector(
    '.theme-switch input[type="checkbox"]'
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM