Search code examples
javascripthtmlcookieslocal-storagestylesheet

Change Stylesheet and save it to "Cookies / Local storage"


I have two stylesheets

<link href="design/default.css" rel="stylesheet" type="text/css" title="default">
<link href="design/new.css" rel="stylesheet" type="text/css" title="new">

and I have buttons what change these stylesheets:

<button class="" onclick="swapStyleSheet('design/default.css')">Default</button>
<button class="" onclick="swapStyleSheet('design/new.css')">New</button>

and of course javascript that swap these stylesheets.

    function swapStyleSheet(sheet){
       document.getElementById('design').setAttribute('href', sheet);
}

The question is:

How to save stylesheets what user clicked on? using Cookies / Local storage.

Even when user leave my page and come back after 4 days.

Is better to use "Cookies" or "Local storage" ?


Solution

  • At load event of window define a variable to store reference to Blob URL. If localStorage has key, for example, "styles", get css from localStorage, create a Blob with localStorage.getItem("styles") set as element of iterable at first parameter, type set to "text/css". Pass Blob to URL.createObjectURL() to set at value of #design .href. Else, filter document.styleSheets for .href which matches sheet parameter at swapStyleSheet call, create get .cssText from .rules property lookup, set as Blob, perform above described procedures.

    window.onload = function() {
      let blob, url;
    
      function setStyle() {
        var sheet = localStorage.getItem("styles");
        blob = new Blob([localStorage.getItem("styles")], {type:"text/css"});    
        url = URL.createObjectURL(blob);
        document.getElementById("design").setAttribute("href", url);
      }
    
      if (localStorage.getItem("style") != null) setStyle();
    
      function swapStyleSheet(sheet) {
    
        var rules = Array.prototype.filter.call(document.styleSheets, function(styles) {
          return styles.href.indexOf(sheet) !== -1
        })[0].rules;
    
        for (var i = 0, css = ""; i < rules.length; i++)  css += rules[i].cssText;
    
        if (url) URL.revokeObjectURL(url);
    
        localStorage.setItem("styles", css);
    
        setStyle();
    
      }
    }