Before posting this I've browsed some existing topics but couldn't get anything helpful, I tried some things to fix this but it failed.
I'm developing a website, and today I wanted to code a basic dark mode switch in Javascript :
<script type="text/javascript">
function switchWhite() {
document.getElementById("body").className = "";
document.getElementById("menubar").className = "navbar navbar-expand-lg navbar-light bg-light";
}
function switchDark() {
document.getElementById("body").className = "dark";
document.getElementById("menubar").className = "navbar navbar-expand-lg navbar-dark bg-dark";
}
function triggerSwitch() {
if ( document.getElementById("body").className.match("dark") ) {
switchWhite();
} else {
switchDark();
}
}
</script>
<button onclick="triggerSwitch()">Switch Mode</button>
This works just fine but there is an auto-refresh on the website, which is triggered every 30 seconds and which refreshes only specific blocs (like menubar) :
<script>
setInterval(function()
{
$(document).ready(function() {
$("#menubar_refresh").load(document.URL + " #menubar");
});
}, 30000);
</script>
Which also works fine, but I cannot mix these two features because once I switch to dark mode theme, after 30 seconds (when the auto-refresh is triggered), it gets back to light mode (the original state of the page).
Though is this normal, so I tried to put the dark mode back right after the bloc refreshes, like this :
<script>
setInterval(function()
{
$(document).ready(function() {
$("#menubar_refresh").load(document.URL + " #menubar");
});
switchDark(); // here
}, 30000);
</script>
It simply doesn't work, the bloc (and only this bloc, not the whole page) still gets back to the original state (light).
I've noticed that it switches to dark mode for a few milliseconds, and gets back to the original state.
I thought that the switchDark(); call is executed at first, even before the whole function finishes, in a way that the dark mode is set and then the bloc is refreshed.
So I tried setting a variable to block the execution of switchDark(); call before everything else finished executing, but the result is the same, which makes me think that my hypothesis is wrong.
Could you please help me to figure out what the problem is here ?
I can add more code snippets if you need them.
Thanks a lot