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 } })
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.
I have to change (cssFileDay.disabled = true) to (cssFileDay.disabled === true) or (cssFileDay.disabled). It started working well.
hold onto. Yes, you found the error. But all four example codes you show in your question have
if
statements likeA single
=
is an attribution command that, in JavaScript (and other C-derived languages), returns a value, so anif
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.