Reputation: 37
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.
Upvotes: 1
Views: 1045
Reputation: 31987
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'))
Upvotes: 0
Reputation: 194
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>
Upvotes: 1