0

I` have a function in jquery witch allow users to change background color of site. But if they refresh the page background-color go to default. How can i use LocalStorage with this jquery function

sessionStorage.setItem("bg_color", "#000");
let personName = sessionStorage.getItem("bg_color");

$(document).ready(function() {
    $('.dark__mode').click(function() {
        $('#headerCustomColor').css("background-color", personName);
        $('#TogleBarWi').css("color", "#fff");
        $('.custom_color_link').css("color", "#fff");
    });
});
6
  • I see this. But dont know how to update to my code
    – leon002
    Feb 7, 2022 at 16:40
  • As i can understand you already have a working code with localStorage. Just replace the word localStorage into sessionStorage.
    – Hakan Kose
    Feb 7, 2022 at 16:42
  • Think what you need example when your document is ready let background = try to get localStorage.getItem('background-color') ? if is true localStorage.getItem('background-color') : else "#default color Than you can set inside your click() event `localStorage.setItem("background-color", "#383838");
    – Hakan Kose
    Feb 7, 2022 at 16:58
  • Okay . Now i can use session storage. But still when i refresh site, background change to default, dont keep color from sessionStorage
    – leon002
    Feb 7, 2022 at 16:58
  • Share your current code
    – Hakan Kose
    Feb 7, 2022 at 16:59

1 Answer 1

0
//You have to check if there is a certain background
// If there is a background color use it else use default
let background = localStorage.getItem("background") ? localStorage.getItem("background") : "#FFF";

// Change header on document loading the background color based on localStorage
$('#headerCustomColor').css("background-color", background);

// On click
$('.dark__mode').click(function() {
    // Set the variable background to custom
    background = "#383838";
    // Set localStorage bg color to custom 
    // This is to enable on refresh so the new bg is set.
    localStorage.setItem("background", background);
    
    // Recolor the header after the click
    $('#headerCustomColor').css("background-color", background);

});
1
  • Thanks! This was hlpfouly
    – leon002
    Feb 7, 2022 at 17:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.