Localstorage

Hello, I haven’t done much coding lately so been reading and started to do a dark theme for my web to keep doing stuff.

I’ve made an icon with: Id = "icon"

And I’ve used jquery to do a toggle class and it works ok, then I’ve been reading about localstorage but I think I’m not understading it right.

This is what i came with:

$(document).ready(function(){
   var x = localStorage.getItem("darkTheme");
});

//if (x === 'on') {
  //darkmodeOn();
//}

$("#icon").click(function(){
    darmodeOn();
    if (!$(".container-fluid").hasClass("darktheme")) {
        darkmodeOff();
    }
});

function darmodeOn(){
    $(".container-fluid").toggleClass("darktheme");
    $("body").toggleClass("darktheme");
    $("#menulogo").attr('src',"imgs/logodark.png");
    $("#icon").attr('src',"imgs/sun.png");
    localStorage.setItem("darkTheme", "on");
}

function darkmodeOff(){
    $("#menulogo").attr('src',"imgs/logo.png");
    $("#icon").attr('src',"imgs/moon.png");
    localStorage.setItem("darkTheme", "off");
}

I want to be able to store it, so you can navigate form page to page or if you go out and come back later to have your selected theme already set.

The switch works, until I uncomment the commented part where I pretend to read the localstorage and do the switch automatically.

You have a typo in your darkmodeOn method name. It says darmodeOn instead of darkmodeOn.

You’re calling the method with the matching typo in your uncommented code, but the commented code is without the typo method call.

1 Like

Hey thanks for that, english not my main. But i Try to do everything in english since most guides, manuals, etc are in english. I double typed that error.

It still didn’t work but i changed and IF and its now working, in case anyone searchs something similar one day:

if(localStorage.getItem('darkTheme') === 'on'){
	darkmodeOn();
} else {
	darkmodeOff();
}

$("#icon").click(function(){
    darkmodeOn();
    if (!$(".container-fluid").hasClass("darktheme")) {
        darkmodeOff();
    }
});

function darkmodeOn(){
    $(".container-fluid").toggleClass("darktheme");
    $("body").toggleClass("darktheme");
    $("#menulogo").attr('src',"imgs/logodark.png");
    $("#icon").attr('src',"imgs/sun.png");
    localStorage.setItem("darkTheme", "on");
}

function darkmodeOff(){
    $("#menulogo").attr('src',"imgs/logo.png");
    $("#icon").attr('src',"imgs/moon.png");
    localStorage.setItem("darkTheme", "off");
}
1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service