search

Home  >  Q&A  >  body text

JavaScript only partially replaces CSS files

I'm trying to replace a CSS file on the page with another CSS file by using an event listener to switch between day/night theme. I tried various methods but none of them quite worked.

My default theme is dark and I can only change it to light theme using my code but not again to dark. What did I do wrong? Thank you all!

colorModeBtn.addEventListener("click", function() {
  if (cssFile.href = "styles.css") {
      cssFile.setAttribute("href", "styles-daylight.css") 
  } else {
    cssFile.setAttribute("href", "styles.css")
  }
})
colorModeBtn.addEventListener("click", function() {
  if (cssFileDay.disabled = true) {
    cssFileDay.disabled = false
    cssFile.disabled = true
  } else {
    cssFileDay.disabled = true
    cssFile.disabled = false
  }
})
colorModeBtn.addEventListener("click", function() {
  const cssLink = document.createElement("link")
  if (cssFile.href = "styles.css") {
    cssLink.rel = "stylesheet"
    cssLink.href = "styles-daylight.css"
    document.head.appendChild(cssLink)
    cssFile.disabled = true
  } else if (document.head.cssLink) {
    document.head.removeChild(cssLink)
    cssFile.disabled = false
  }
})
colorModeBtn.addEventListener("click", function() {
  const cssLink = document.createElement("link")
  if (cssFile.href = "styles.css") {
    cssLink.rel = "stylesheet"
    cssLink.href = "styles-daylight.css"
    document.head.appendChild(cssLink)
    cssFile.disabled = true
  } else if (document.head.cssLink) {
    var linkNode = document.querySelector('link[href*="styles-daylight.css"]')
    linkNode.removeChild(linkNode)
    cssFile.disabled = false
  }
})

P粉322106755P粉322106755295 days ago407

reply all(2)I'll reply

  • P粉012875927

    P粉0128759272024-03-23 09:07:11

    I found the answer, it's just a small thing, like in this case. However, I don't understand why it doesn't work the way I posted above.

    That's what I'm using.

    colorModeBtn.addEventListener("click", function() {
      if (cssFileDay.disabled = true) {
        cssFileDay.disabled = false
        cssFile.disabled = true
      } else {
        cssFileDay.disabled = true
        cssFile.disabled = false
      }
    })

    I have to change (cssFileDay.disabled = true) to (cssFileDay.disabled === true) or (cssFileDay.disabled). It started working well.

    reply
    0
  • P粉025632437

    P粉0256324372024-03-23 00:40:22

    hold onto. Yes, you found the error. But all four example codes you show in your question have if statements like

    if (x = true)

    A single = is an attribution command that, in JavaScript (and other C-derived languages), returns a value, so an if statement will always be true.

    The comparison you want is the double equal sign (==).

    The triple equal sign (===) is also a comparison, but it also compares the data types on the left and right sides.

    reply
    0
  • Cancelreply