javascripthtmlcssmodesessionstorage

Using sessionstorage for saving dark mode


I successfully added dark mode to my site using This fiddle

JS:

$('#mode').change(function(){   

if ($(this).prop('checked'))
{
    $('body').addClass('dark-mode');
}
else
{
    $('body').removeClass('dark-mode');
}
});

However, when refreshing the page the theme switches back obviously. I can't find out how to use sessionstorage to keep dark mode over the domain.

Can someone help me? Thanks!


Solution

  • You can use local storage for storing the data

    function darkmode(){
        $('body').addClass('dark-mode');
        localStorage.setItem("mode", "dark");
        }
    
    
    
    function nodark(){
            $('body').removeClass('dark-mode');
            localStorage.setItem("mode", "light");
            }
    
      if(localStorage.getItem("mode")=="dark")
            darkmode();
      else
        nodark();
    
    $('#mode').change(function(){   
    
        if ($(this).prop('checked'))
        {
            darkmode();
        }
        else
        {
            nodark();
        }
    
    });