Solution 1 :

You can use localStorage to this;

<script>
 function swapStyleSheet(sheet) {
   localStorage.setItem('style', sheet);
   document.getElementById('pagestyle').setAttribute('href', sheet);
 }
 
 function applyStyleSheet() {
   // restore style
   const sheet = localStorage.getItem('style') || 'style-green.min.css';
   document.getElementById('pagestyle').setAttribute('href', sheet);
 }
 
 applyStyleSheet();

</script>

Solution 2 :

You can store the href in localStorage.

To save it, you can use:

localStorage.setItem('csshref', href);

And on page load, you can do:

swapStylesheet(localStorage.getItem('csshref'))

Problem :

I have a different couple of themes on my website, and there is a dropdown menu with buttons where you can switch your theme. Here is how I have it set up:

<script>
  function swapStyleSheet(sheet) {
    document.getElementById('pagestyle').setAttribute('href', sheet);
  }
</script>

Then here’s the button this is attached to:

<button onclick="swapStyleSheet('style-green.min.css')">Green Theme</button>

This works great; however, whenever I hit the refresh button on my screen, it switches back to the original stylesheet that was first attached to the page. I want it to keep whatever stylesheet it was switched to on refresh. How do I do this? Is there something I can add to my tag that will let me store some type of session/data?

Thanks.

Comments

Comment posted by jchillin111

Thanks as well, appreciate the detail – this is super helpful!

Comment posted by jchillin111

Thank you for your answer! I’ll try it out 🙂

Comment posted by Spectric

@jchillin111 No problem. If it answers your question, please consider accepting

By