I am looking to incorporate a dark mode switch and I need it to switch to an image when doing so but can't figure it out.
I tried a couple options at the bottom but can't figure it out.
I've done some searching about to find an answer but can't seem to get anything to work inside of what I have already.
Any help much appreciated.
<div class="title">
<div class="logo">
<a id="logo-home" href="index.html">
<img src="/Public/Images/light-image.png" class="light-theme-logo" style="width: 100%;">
<img src="/Public/Images/dark-image.png" class="dark-theme-logo">
</a>
</div>
</div>
.logo {
display: flex;
flex-wrap: wrap;
width: 80px;
height: auto;
}
.light-theme-logo {
display: block;
}
.dark-theme-logo {
display: contents;
}
const MOON = '🌙';
const SUN = '☀️';
const DARK_MODE = 'dark';
const LIGHT_MODE = 'light';
const DEFAULT_MODE = LIGHT_MODE;
const btn = document.querySelector('#theme-switcher');
init();
function init() {
let storedMode = sessionStorage.getItem('mode');
if (!storedMode) {
storedMode = DEFAULT_MODE;
sessionStorage.setItem('mode', DEFAULT_MODE);
}
setMode(storedMode);
}
function setMode(mode = DEFAULT_MODE) {
if (mode === DARK_MODE) {
btn.textContent = SUN;
document.body.classList.add(DARK_MODE);
} else if (mode === LIGHT_MODE) {
btn.textContent = MOON;
document.body.classList.remove(DARK_MODE);
}
}
btn.addEventListener('click', function() {
let mode = sessionStorage.getItem('mode');
if (mode) {
let newMode = mode == DARK_MODE ? LIGHT_MODE : DARK_MODE;
setMode(newMode);
sessionStorage.setItem('mode', newMode);
}
})
function setLogo(mode = DEFAULT_MODE) {
if (mode === DARK_MODE) {
btn.textContent = SUN;
document.body.classList.add(DARK_LOGO);
} else if (mode === LIGHT_MODE) {
btn.textContent = MOON;
document.body.classList.remove(DARK_LOGO);
}
};
function logoSwap() {
if (mode === LIGHT_MODE) {
document.body.classList.add("Images/Light-Image.png");
} else if (mode === DARK_MODE) {
document.body.classList.remove("Images/Dark-Image.png");
}
};
Managed to figure it out, and it was simpler than I was making it out to be.
function setMode(mode = DEFAULT_MODE) {
if (mode === DARK_MODE) {
btn.textContent = SUN;
document.body.classList.add(DARK_MODE);
document.getElementById("light-theme").src = "Images/Dark-Image.png";
} else if (mode === LIGHT_MODE) {
btn.textContent = MOON;
document.body.classList.remove(DARK_MODE);
document.getElementById("light-theme").src = "Images/Light-Image.png";
}
}