JavaScript only partially replaces CSS files
P粉322106755
P粉322106755 2024-03-22 09:33:43
0
2
400

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粉322106755
P粉322106755

reply all(2)
P粉012875927

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.

P粉025632437

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template