I want to let the user switch between light and dark mode. The switch is working and also the 2 themes work. But when I have dark mode enabled and I refresh te page, the light theme loads in for about 1/2 seconds and after that it switches to dark mode. All my colors are defined with :root {...} & .dark-theme{...} in an sass file.
The dark modes load in with localstorage which I execute when the page is loaded. I tried an async function but that didn't work. Altough I don't know if I did it right.
function checkTheme() {
return new Promise(function(resolve, reject) {
const userPreference = localStorage.getItem('theme');
if (userPreference === "dark") {
// Als de gebruiker het donkere thema verkiest, voeg de donkere thema-klasse toe aan de body
document.body.classList.add("dark-theme");
// Zet de checkbox op "Dark Mode"
document.getElementById("themeToggle").checked = true;
}
resolve();
});
}
this is my function where I execute the check on which theme needs to be selected.
window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
openNextServiceTab(2);
}
Promise.all([
checkTheme(),
loadFilters(),
fillDropdown(),
initMap(),
]);
if (window.location.pathname == '/login') {
document.body.style.overflow = 'hidden';
}
}
This is the function where the function gets executed.
:root {
--primary-color: #0B1505;
--secondary-color: #FFFFFF;
--background-gray : rgb(11,21,5);
--linearbackground-gray : linear-gradient(0deg, rgba(11,21,5,1) 0%, rgba(84,84,84,1) 100%);
--background-green :rgb(117,247,75);
--linearbackground-green: linear-gradient(100deg, rgba(117,247,75,1) 0%, rgba(84,84,84,1) 100%);
--background-gray-green : rgb(11,21,5);
--linearbackground-gray-green: linear-gradient(0deg, rgba(11,21,5,1) 0%, rgba(84,84,84,1) 100%);
--border: 1px solid #0B1505;
--gray : #726f6f;
--green: #75F74B;
--input-gray: #2E332B;
--thead: #3C9673;
--input-border : transparent;
}
.dark-theme {
--primary-color: #FFFFFF;
--secondary-color: #0B1505;
--background-gray : rgba(11,21,5, 0);
--linearbackground-gray : rgba(11,21,5, 0);
--border: 1px solid #3C9673;
--gray : #3C9673;
--background-green : #3C9673;
--linearbackground-green: #3C9673;
--background-gray-green : #3C9673;
--linearbackground-gray-green: #3C9673;
--green: #3C9673;
--input-gray: #FFFFFF;
--input-border : 1px solid #3C9673;
--thead: #f1f1f1;
}
This is where my colors are getting defined.