简体   繁体   中英

how to save dark-mode preference by using session storage

I'd like to store user's preferences on dark-mode by using session storage.
The code below is the toggle function for the dark mode.

function toggleDarkMode() {
    var dataTheme = $('body').attr('data-theme');

    if(dataTheme === 'dark') {
        $('body').attr('data-theme', 'light');
    } else {
        $('body').attr('data-theme', 'dark');
    }
};  

when firing dark mode, I change the data-theme of body tag of JSP file such as <body data-theme="light"> to <body data-theme="dark">

You have to use sessionStorage for this purpose:

To store a value: sessionStorage.setItem(key,value);
To access a value: sessionStorage.getItem(key);

function toggleDarkMode()
{
//Check if there is a value in Session Storage or Not!
if(sessionStorage.getItem('theme') != '')
{
    $('body').attr('data-theme', 'light');
}
else
{
    theme=sessionStorage.getItem('theme');  //Get Value of theme from session
    $('body').attr('data-theme',theme);  
}
var dataTheme = $('body').attr('data-theme');

if(dataTheme === 'dark') {
    $('body').attr('data-theme', 'light');
    sessionStorage.setItem("theme", "light"); // Store the value in Session Storage
} else {
    sessionStorage.setItem("theme", "dark"); // Store the value in Session Storage
    $('body').attr('data-theme', 'dark');
}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM