Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remembering a users button press

I have created the following code in order to allow the user to change the stylesheet of my website from light to dark.

<div class="style-changer"><span>Change Style:</span>
<button class="white" onclick="swapStyleSheet('white.css')">Light</button>
<button class="black" onclick="swapStyleSheet('black.css')">Dark</button>
</div>

<link id="pagestyle" rel="stylesheet" type="text/css" href="white.css">
<script>function swapStyleSheet(sheet){ document.getElementById('pagestyle').setAttribute('href', sheet);}</script>

That code currently sets the default stylesheet as white.css whenever the page is loaded, and then changes it to dark css when the dark button is clicked.

What I want to do is make it set a cookie so that the site remembers the dark button has been pressed and then loads dark.css as the default, instead of loading white.css as it normally would.

If anyone could help me add some code to this to make it do that I would appreciate it as I'm a bit of a noob when it comes to javascript and cookies.

Thanks.

Update: I have made some code using some suggestions with local storage, however I reckon I might have got it completely wrong, here's a link:

https://jsfiddle.net/zy360m7m/3/

like image 724
NGriffin Avatar asked Mar 16 '23 09:03

NGriffin


1 Answers

You have some options. Here are a couple popular ones:

1) You can use localStorage which acts as a cache which persists depending on the user's browser settings.

localStorage.setItem('darkWasPressed', 'true');

localStorage.getItem('darkWasPressed'); // returns 'true'

2) A non-persistent alternative is sessionStorage which allows a global object to exist with the tab or window that is open.

sessionStorage.setItem('darkWasPressed', 'true');

sessionStorage.getItem('darkWasPressed'); // returns 'true'

3) You can also just create a cookie. Doing this is as simple as:

document.cookie = 'darkWasPressed=true';

And then, you can just retrieve it using "document.cookie", but getting the right cookie and value takes a little parsing to do.

4) To help make #3 easier, we can use a simple reader/writer library.

Here is how we can use cookies using the library documented here:

docCookies.setItem('darkWasPressed', 'true');

docCookies.getItem('darkWasPressed'); // returns 'true'
like image 173
boombox Avatar answered Mar 30 '23 00:03

boombox