Search code examples
javascriptcssstylesheet

Store CSS or HTML in localStorage


I have this function to toggle a dark mode on and of with a single button. It checks if the dark.css stylesheet is already added to the site, if yes it removes it. If there isn't a dark.css it loads it and appends it to the head.

Now I want to store this information in the localStorage so the browser remembers whether the dark.css should be loaded or not.

$(function() {
$('#toggler').click(function(){
    if ($('link[href*="css/dark.css"]').length) {
        $('link[href*="css/dark.css"]').remove();
    }
    else {
        var lightMode = document.createElement('link');
        darkMode.rel="stylesheet";
        darkMode.href="css/dark.css";
        document.getElementsByTagName('head')[0].appendChild(darkMode);
    }
});
})

Solution

  • All you have to do is check localStorage in your jQuery function. Preferably earlier in the function (so DOM is updated quickly in case you have some intensive code elsewhere), though not required.

    $( function () {
    
      function appendDarkMode() {
    
        var darkMode = document.createElement( 'link' );
    
        darkMode.rel  = 'stylesheet';
        darkMode.href = 'css/dark.css';
    
        document.getElementsByTagName( 'head' )[ 0 ].appendChild( darkMode );
    
      }
    
      // This is run when page is first loaded.
      if ( localStorage ) {
    
        var useDarkMode = localStorage.getItem( 'useDarkMode' );
    
        // The boolean we set in the click handler will become a string.
        useDarkMode === 'true' ? appendDarkMode() : localStorage.setItem( 'useDarkMode', false );
    
      }
    
      // Theme click handler.    
      $( '.toggler' ).on( 'click', function ( e ) {
    
        var $darkModeLink = $( 'link[href*="css/dark.css"]' );
    
        $darkModeLink.length ? $darkModeLink.remove() : appendDarkMode();
    
        if ( localStorage ) {
    
          // Note that we're inverting the value here. By the time this
          // is run, we will have changed whether or not `dark.css` is
          // on the page. Which is opposite the initial value of
          // `$darkModeLink`.
          localStorage.setItem( 'useDarkMode', !$darkModeLink.length  );
    
        }
    
      } );
    
    } );