1

I need to make a cookie which will remember the css stylesheet preference.

I switch stylesheets as:

function swapStylesheet(sheet){

    document.getElementById('pagestyle').setAttribute('href', sheet);

}

And call it from buttons:

<a button class="Button" onclick="swapStylesheet('DayStyle.css')">Light</a>
        
<a button class="Button" onclick="swapStylesheet('NightStyle.css')">Dark</a>

So it changes the href to the css file of choice, but on refresh it changes back to default. Any way to create a cookie to remember the href preference? And can it be for all of the site?

Giorgos Cut
  • 67
  • 1
  • 5
  • Does this answer your question? [Persist variables between page loads](https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads) –  Nov 04 '20 at 12:20
  • To define a cookie: https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript – ZecKa Nov 04 '20 at 12:20

1 Answers1

2

You could use the localStorage of your browser since the use of cookies is mostly intended for reading data server-side (but you could still use cookies if you really want to).

Obviously you could also use sessionStorage, though the preferred theme won't be available after the tab/browser is closed because, as the name suggests, a sessionStorage is not kept when the session is closed. This would defeate the purpose of remebering a user preference..

Approach with localStorage:

When the user selects the style, you can:

function swapStylesheet(sheet){
    document.getElementById('pagestyle').setAttribute('href', sheet);
    localStorage.setItem('stylesheet', sheet);
}

And when initially loading the page you could use the <body onLoad ="checkLS()"> function to check if localStorage is set and apply style:

function checkLS () {
    let sheet = localStorage.getItem('stylesheet');
    if (sheet) {
        swapStylesheet(sheet){
    };
}

This way the users preferred stylesheet/theme is automatically set even if the browser was closed between visits..

iLuvLogix
  • 5,920
  • 3
  • 26
  • 43