I've made a dark mode toggle button for my demo website that adds a class to change the background color. The button works, but I want to swap out the image the button is using depending on if the class is present. It's not working. I think I've messed up MutationObserver somehow, can anyone help?
let buttonIMG = document.getElementById("darkButtonIMG");
const observer = new MutationObserver(darkImage);
observer.observe(buttonIMG, {
attributes: true
});
function darkImage() {
let buttonIMG = document.getElementById("darkButtonIMG");
let buttonSRC = buttonIMG.hasAttribute("dark");
if (buttonSRC === true) {
buttonIMG.setAttribute("src", "images/Sun_Icon.png");
} else {
buttonIMG.setAttribute("src", "images/Moon_Icon.png");
}
}
HTML
<nav>
<div class="row">
<button class="buttonHide" id="hamburgerBtn">☰</button>
<ul id="navOpen">
...
<li><button id="darkButton" type="button" class=""><img id="darkButtonIMG"src="images\Moon_Icon.png" alt="Dark mode icon"></button></li>
</ul>
</div> <!-- End of Navbar Row -->
</nav>
I want to swap out the image the button is using depending on if the class is present.
I'm assuming that when you click the button you're adding class dark to it.
In your callback method you're checking for the presence of dark attribute, but you should check for the presence of a class instead.
let buttonSRC = buttonIMG.classList.contains("dark");
You need to setAttribute for check hasAttribute
let buttonIMG = document.getElementById("darkButtonIMG");
const observer = new MutationObserver(darkImage);
observer.observe(buttonIMG, {
attributes: true
});
function darkImage() {
let buttonIMG = document.getElementById("darkButtonIMG");
let buttonSRC = buttonIMG.hasAttribute("dark");
if (buttonSRC === true) {
buttonIMG.setAttribute("src", "images/Sun_Icon.png");
buttonIMG.removeAttribute("dark");
} else {
buttonIMG.setAttribute("src", "images/Moon_Icon.png");
buttonIMG.setAttribute("dark", "dark");
}
}