I have a code that allows me to easily switch from light mode to dark mode without having to write css for dark mode, it works with two buttons, each executing either the light mode or dark mode depending on your choice of click. However i want to merge this two functions into one single button so that it can be used to toggle the function. If anyone answering does include how it can be used with a toggle button, that won’t be bad at all… The code i am using is
const htmlEl = document.getElementsByTagName('html')[0];
const toggleTheme = (theme) => {
htmlEl.dataset.theme = theme;
}
html {
transition: color 300ms, background-color 300ms !important;
}
html[data-theme='dark'] {
background: #000;
filter: invert(1) hue-rotate(180deg)
}
html[data-theme='dark'] img {
filter: invert(1) hue-rotate(180deg)
}
<button onclick="toggleTheme('dark');">Dark Mode Test</button>
<button onclick="toggleTheme('light');">Light Mode Test</button>
<br><font color="red">WE ARE RED</font>
<br><font color="blue">WE ARE BLUE</font>
<br><font color="black">WE ARE Black</font>
Then i tried to execute the switch using Eventlisteners this way
<script>
var btn = document.getElementById('navbtn');
btn.addEventListener('click', function() {
var foo = 'dark';
if (foo === "light") {
toggleTheme('dark');
} else {
toggleTheme('light');
}
}, false);
</script>
This however only reacts on first click and not on second. What could be the best way to achieve this? Thanks in anticipation.