I noticed that if the person is in light mode and switches to dark mode and refreshes the page it continues in dark mode, now if the person is in dark mode and switches to light and refreshes the page it does not work page back for dark.
// Get current theme
var theme = localStorage.getItem( 'theme' );
// Set defaults if theme is not defined.
if ( ! theme ) {
localStorage.setItem( 'theme', 'light' );
theme = 'light';
}
// Add theme to the body.
document.body.classList.add( theme );
// Handle onClick events
document.getElementById( 'theme-toggle' ).addEventListener( 'click', () => {
// Cleanup classes from body.
document.body.classList.remove( 'light' );
document.body.classList.remove( 'dark' );
// Change the theme.
theme = ( theme === 'light' ) ? 'dark' : 'light';
// Save the theme.
localStorage.setItem( 'theme', theme );
// Apply the theme.
document.body.classList.add( theme );
});
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.body.classList.remove( 'light' );
document.body.classList.remove( 'dark' );
var theme = 'dark';
localStorage.setItem( 'theme', theme );
document.body.classList.add( theme );
}
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
document.body.classList.remove( 'light' );
document.body.classList.remove( 'dark' );
var newColorScheme = event.matches ? "dark" : "light";
localStorage.setItem( 'theme', newColorScheme );
document.body.classList.add( newColorScheme );
});