Comencé a crear un sitio web personal con un interruptor de palanca y estoy buscando una manera de mantenerlo activado incluso cuando navego a otra página de mi sitio web.
aquí está el JavaScript que usé:
btn.addEventListener('click', function () { document.body.classList.toggle('dark-theme'); })Cualquier ayuda es muy apreciada, gracias!
Como parece que quieres usar un tema oscuro y claro en tu sitio web, puedo darte un ejemplo de cómo resolví este problema:
JavaScript:
function changeTheme(){ //function to change Theme on button click //function switches css class if(document.body.classList.contains('light')){ document.body.classList.remove('light'); document.body.classList.add('dark'); document.cookie = "Color=dark;" }else{ document.body.classList.remove('dark'); document.body.classList.add('light'); document.cookie = "Color=light;" } } $(document).ready(function() { //calls function every time your webpage loads and checks which theme is selected if(getCookie("Color")!= ""){ if(getCookie("Color")=="dark"){ changeTheme(); } } }); function getCookie(cname) { //Helper function to check what theme is currently selected var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; }CSS (aquí están las clases para cambiar las variables css de claro a oscuro y viceversa:
.light{ --footer-background: rgb(189, 189, 189); --footer-textcolor: rgb(14, 14, 14); --body-backgroundcolor:rgb(255, 255, 255); --body-font-color: rgb(27, 27, 27); --scrollbar-track: rgb(192, 192, 192); --scrollbar-thumb: rgb(114, 114, 114); } .dark{ --footer-background: rgb(59, 55, 55); --footer-textcolor: rgb(238, 238, 238); --body-backgroundcolor:rgb(17, 17, 17); --body-font-color: rgb(194, 194, 194); --scrollbar-track: rgb(39, 39, 39); --scrollbar-thumb: rgb(20, 20, 20); }Espero poder ayudar