I've been trying to implement a persistent dark mode onto my website on Squarespace. When the user clicks the dark mode, we want to to fade in and out of said mode, and have been using the following CSS/JS to do so:
CSS Snippet:
.dark-mode {
span {
color: #fff !important;
transition: color 0.5s !important;
}
.section-background,
.site-wrapper {
background-color: #151515 !important;
transition: background 0.5s !important;
}
}
JS:
$('.dark-mode-toggle').on('click', function(e) {
$('body').toggleClass("dark-mode"); //you can list several class names
e.preventDefault();
if (document.body.classList.contains('dark-mode')) { //when the body has the class 'dark' currently
localStorage.setItem('darkMode', 'enabled'); //store this data if dark mode is on
} else {
localStorage.setItem('darkMode', 'disabled'); //store this data if dark mode is off
}
});
if (localStorage.getItem('darkMode') == 'enabled') {
document.body.classList.toggle('dark-mode');
$("i.fas").addClass("fa-sun");
}
I'm aware that this is messy, as I'm still getting used to JS/JQuery, so I'm using a mix of both. When the page loads, however, the page will flash for the specified animation time, as if it has just been clicked. How do I stop this from happening?