mystyle-js is a simple and lightweight JavaScript library, which enables developers to let their website visitors apply a custom css stylesheet.
- Download the latest release
- Drop either the production version (
dist/mystyle.min.js
) or the non-minified development version (dist/mystyle.js
) into your project folder - Link it in your HTML code (e.g.
<script src="../js/mystyle.min.js"></script>
) - Done!
The developer needs to implement his own method of getting the css stylesheet from his users, one method using JavaScripts FileReader
class is shown in the demo.
To be able to use mystyle-js, you need to initialize a new mystyle-js object:
<script src="../js/mystyle.min.js"></script>
<script>
var mystyle = new MyStyleJS('your-css-id');
</script>
- Note:
your-css-id
is just a regular HTML element id, used to identify the added stylesheet later on. This can be any valid HTML id of your choice.
Then you need to load your CSS stylesheet. mystyle-js comes with two different methods to do this.
- Loading the stylesheet from a string (e.g. a read file)
- Load the stylesheet from the page's
window.localStorage
orwindow.sessionStorage
(Webstorage API)
Constructor of the MyStyleJS class.
id
is a HTML id applied to the loaded stylesheet for later recognition.- This is used as the content of a
id=""
attribute.
- This is used as the content of a
var mystyle = new MyStyleJS('customstyle-example');
Loads a css stylesheet from the css
parameter.
css
is a css stylesheet as plaintext
mystyle.loadCSSfromString("body { background-color: red; }");
Saves the loaded css from the MyStyleJS
instance to the users WebStorage
.
persistent
defines the saving location of the css stylesheet.- If
true
, the data will be saved to thelocalStorage
and will be kept until it's manually deleted. - If
false
, the data will be saved to thesessionStorage
and will be deleted, if the browser (or tab) is closed.
- If
mystyle.loadCSSfromString("body { background-color: green;}");
mystyle.saveCSS(true):
Loads any saved css stylesheets from the users WebStorage
, prioritizing the (non-persistent) sessionStorage
.
mystyle.loadCSS();
Removes any loaded custom css stylesheets from the website and from the users WebStorage
.
mystyle.clearCSS();
Actually applies the css stylesheet to the website, if css was loaded manually.
Note:
loadCSSfromString(css: string)
already callsapplyCSS()
, another call is not needed in this case.
mystyle.css = "body { background-color: blue; }";
mystyle.applyCSS();
There are two ways to view the demo
- View the most up-to-date demo here (GitHub Pages)
- Download/Clone this repository to your computer and open the
demo/index.html
file in your favorite webbrowser.
You use mystyle-js in your project? Feel free to contact me, then I may add you and your project here.