skip to Main Content

I have a small problem I have a theme switch button that turn the page to dark mode, but if I am in the home page and change to contact page the theme switch stops working, but this happens only on the other pages except the main one, and I don’t know how to fix it. I have tried to mess around with the js code, but nothing.

Here is my JavaScript code:

// DarkMode
let darkmode = localStorage.getItem("darkmode")
const themeSwitch = document.getElementById("theme-switch")

const enableDarkmode = () => {
    document.body.classList.add("darkmode")
    localStorage.setItem("darkmode", "active")
    document.getElementById("logo").src="../Imgs/logo-white.png"
}

const disableDarkmode = () => {
    document.body.classList.remove("darkmode")
    localStorage.setItem("darkmode", null)
    document.getElementById("logo").src="../Imgs/logo-blue.png";
}

if (darkmode ==="active") enableDarkmode()

themeSwitch.addEventListener("click", () => {
    darkmode = localStorage.getItem("darkmode")

    darkmode !== "active" ? enableDarkmode() : disableDarkmode()
})

2

Answers


  1. Chosen as BEST ANSWER

    The error occurred because the theme-switch functionality also updates an image on the homepage. Since the image is only present on the homepage, attempting to modify it on another page where it doesn't exist resulted in a null value being returned.

    Here is the updated code:

    // DarkMode
    let darkmode = localStorage.getItem("darkmode")
    const themeSwitch = document.getElementById("theme-switch")
    
    const enableDarkmode = () => {
        document.body.classList.add("darkmode")
        localStorage.setItem("darkmode", "active")
        // document.getElementById("logo").src="../Imgs/logo-white.png"
    }
    
    const disableDarkmode = () => {
        document.body.classList.remove("darkmode")
        localStorage.setItem("darkmode", null)
        // document.getElementById("logo").src="../Imgs/logo-blue.png";
    }
    
    if (darkmode ==="active") enableDarkmode()
    
    themeSwitch.addEventListener("click", () => {
        darkmode = localStorage.getItem("darkmode")
    
        darkmode !== "active" ? enableDarkmode() : disableDarkmode()
        darkmode === "active" ? document.getElementById("logo").src="../Imgs/logo-blue.png" : document.getElementById("logo").src="../Imgs/logo-white.png";
    })
    

    Thanks everyone for your time and sorry for wasting it


  2. You are missing an else statement, so if you are in light mode, the light mode logo does not get displayed when a new page loads. Other than that, your code works fine for me.

    if (darkmode ==="active") enableDarkmode()
    else disableDarkmode()  // EDIT Add this
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search