Motion Motion - 3 months ago 8
CSS Question

How to create class in a custom CSS file by JavaScript?

I want to create a CSS class at runtime using JavaScript and write in a custom CSS file.

Now I wrote the code (see below) and created my class but I don't know how to create it in my CSS file.



var sheet = document.createElement('style')
sheet.innerHTML = ".context-menu-icon-case1:before{content: url(progressbar.png);}";
document.body.appendChild(sheet);





It creates the CSS class in my current page but I want to create it in a custom css file.

Answer

You can request the existing .css file using XMLHttpRequest() or fetch() instead of loading the file at html, append the new style rule to the .css file at XMLHttpRequest.responseText or response.text(), or using FileReader.

Create a Blob or File object, or encoded text representation of new css text appended to existing file, create a <link> element with rel attribute set to stylesheet, href attribute to an objectURL, data URI or encoded text of the created file, append the link element to document.head.

<head>
  <script>
    var cssupdate = `.context-menu-icon-case1:before {
                       content: url(progressbar.png);
                    }`;
    var cssfile = "style.css";
    fetch(cssfile)
    .then(response => response.text())
    .then(currentcss => {
      var css = currentcss + "\n" + `${cssupdate}`;
      var link = document.createElement("link");
      link.rel = "stylesheet";
      link.type = "text/css";
      link.href = "data:text/css," + encodeURIComponent(css); 
      document.querySelector("head").appendChild(link);
    });
  </script>
</head>

plnkr http://plnkr.co/edit/Gh0qR4CcQPROXCldX9OC?p=preview

Comments