I have managed to get a light-dark mode toggle working on my website, but am struggling to figure out how I would implement cookies or localstorage to call upon the user's preferred theme when changing pages on the site.
What I am working with is an external JS file consisting of:
const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)');
const toggle = document.querySelector('.toggle');
const html = document.querySelector('html');
html.dataset.dark = localStorage.dark || prefersDarkMode.matches;
toggle.addEventListener('click', () => {
localStorage.dark = !(html.dataset.dark == 'true');
html.dataset.dark = localStorage.dark;
});
Which is then used in the style sheets by choosing between separate styles with:
html[data-dark="false"]{...}
html[data-dark="true"] {...}
I am very new to JS, which I am sure shows, and have only gotten to this point with the help of peers. I've done my best to try solutions from other answers here as well as learn more about localstorage and cookies through resources like the Mozilla docs but am struggling. A solution or being pointed in the right direction would be greatly appreciated, thank you.
Edit: To clarify on what I am trying to achieve; I would like it so that user theme preferences are saved and applied to all pages while what I currently have only saves an individual page's user preferences, meaning they would manual have to toggle them each time.