How to allow the choice of a theme on the site, through a css file and cache memory?

Asked

Viewed 47 times

1

all right? So, I’m trying to create an individual theme choice system on my site, and with that, I need that, when a user chooses it, it gets saved in the browser cache, and all pages of the site load the css file containing the theme (yellow.css, blue.css), and whenever the user enters, the chosen theme is applied. I’ve tried to hack a code that stores a background image, and displays it whenever the page is accessed, and with another code that makes the page load a css file.

    if (localStorage.background) 
     document.body.background = localStorage.getItem("background");

    function bac(){
    localStorage.setItem("background", "img/14.png");
    document.body.background = "img/14.png";
    }

and

  function changeCSS(cssFile, cssLinkIndex) {
    var oldlink = document.getElementsByTagName("link").item(cssLinkIndex);

    var newlink = document.createElement("link");
    newlink.setAttribute("rel", "stylesheet");
    newlink.setAttribute("type", "text/css");
    newlink.setAttribute("href", cssFile);

    document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
  }
<a href="#" onclick="changeCSS('positive.css', 0);">STYLE 1</a>

What code should I use? Thanks for the answer.

  • If it is a system with BD, you can request that a theme be chosen after login, and save the information to always load the theme such. In terms of UX is much better :)

1 answer

0

You can save which theme was chosen through localStorage.

localStorage.setItem('tema', 'branco');

To recover the saved value use the method localStorage.getItem

var tema = localStorage.getItem('tema');

  • OK, but how do I associate the CSS file to the chosen theme?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.