I am trying to replace a CSS file with another one on a page by toggling between the day/night themes using an eventlistener. I tried to do this in numerous ways, but none of them worked completely.
My default theme is dark and I can only manage to change it to light theme using my code, not back to dark again. What am I doing wrong? Thanks a lot everyone!
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
}
})
CodePudding user response:
I found out the answer and it's a small thing, as usual in this cases. However, I don't understand why it didn't work the way I posted it above.
That was I was using.
colorModeBtn.addEventListener("click", function() {
if (cssFileDay.disabled = true) {
cssFileDay.disabled = false
cssFile.disabled = true
} else {
cssFileDay.disabled = true
cssFile.disabled = false
}
})
And I had to change (cssFileDay.disabled = true) either to (cssFileDay.disabled === true) or (cssFileDay.disabled). And it started working well.
CodePudding user response:
Hold on. Yes you found the error. But ALL four of the sample code you showed on your question have if
statements like
if (x = true)
The single =
is an attribution command that, in JavaScript (and other C derivative languages), return a value so the if
statement will always be true.
The comparison, which is what you want is a double equal (==
).
The triple equal (===
) is also a comparison but it compares the data type between the left and right sides as well.