No puedo entender cómo guardar la selección para el modo oscuro/claro como una cookie.
Aquí está la página web en la que lo estoy probando: https://schooloffish.info/index.html
Probé el código w3schools para las cookies pero no puedo hacer que funcione. Cualquier ayuda es apreciada.
Utilice document.cookie :
// inside your event listener on the dark mode toggle: document.cookie = "darkMode=true";A continuación, puede utilizar una función auxiliar de stock como getCookie() para recuperar el valor:
let darkMode = getCookie("darkMode");Puede usar localStorage con variables css para almacenar y cambiar de tema. Por ejemplo:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> /* css variables */ .dark { --bg: black; --fg: white; } .white { --bg: white; --fg: black; } body { /* use the variable */ background-color: var(--bg); color: var(--fg); } button { /* use the variable */ background-color: var(--bg); color: var(--fg); border-radius: 5px; border-style: dashed; } </style> </head> <body> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ad at ipsum placeat maiores, fugiat neque sit, et consequatur, fuga libero magni porro saepe distinctio quibusdam sapiente praesentium earum assumenda id!</p> <button id='switch' onclick="switchTheme()">switch theme</button> <script> // setting theme when contents are loaded window.addEventListener('load', function () { var theme = localStorage.getItem('theme'); // when first load, choose an initial theme if (theme === null || theme === undefined) { theme = 'light'; localStorage.setItem('theme', theme); } // set theme var html = document.querySelector("html"); // apply the variable html.classList.add(theme); }) function switchTheme() { var theme = localStorage.getItem('theme'); var html = document.querySelector('html'); // choose new theme if (theme === 'dark') { new_theme = 'light'; } else { new_theme = 'dark'; } // remove previous class html.classList.remove(theme); // add new class html.classList.add(new_theme); // store theme localStorage.setItem('theme', new_theme); } </script> </body> </html>