Store User Preferences With Cookies

cookies screenshot

cookies screenshot

If you’ve read the snippet ‘Simple Javascript Stylesheet Changer’, you’ll no doubt be wanting to store the user preferences across the site. This can easily be done with the use of cookies.


Cookies are small bits of data that are stored on the user’s browser as a way to identify that particular user. By setting and reading these stored cookies, we can present specific information/styles to the user every time they revisit our site.

Setting A Cookie

You set a cookie by using the document.cookie property.

1
document.cookie = "name=value";

By default, the cookie only persists until the browser is closed. If you want the cookie to have a longer life than that, you need to specify a time in the future. You do this by using the max-age attribute. This takes a length of time expressed in seconds..

1
document.cookie = "name=value; max-age=" + 60;

There are other optional attributes you can use in your cookie, each one separated from the next by a semi-colon. However, because the default behaviour is generally ok and also to keep this snippet brief, I won’t bother going in to them here.

Reading Cookies

Once you’ve set a cookie, you need to check for its presence on subsequent pages of your site. To do this , you split document.cookie into an array.

1
myCookieArray = document.cookie.split("; ");

This splits the cookie into an array of name/value pairs separated by the semi-colon. We want to reference the first name/value pair as that’s where we stored our value. The following code accesses the first name/value pair and then splits that into two parts using = as the separator.

1
2
myCookieArray = document.cookie.split("; ");
myCookiePair = myCookieArray[0].split("=");

We can then retrieve our cookie value like this:

1
2
3
myCookieArray = document.cookie.split("; ");
myCookiePair = myCookieArray[0].split("=");
myCookieValue = myCookiePair[1];

Remember that the array index starts at ‘0′ so myCookiePair[0] is the name of our cookie and myCookiePair[1] is the value.

Deleting Cookies

To erase a cookie, we simply recreate it without a value and give a max-age attribute of 0:

1
document.cookie = "name=; max-age=" + 0;

Stylesheet Changer With Cookies

To enable cookies on the original ‘Simple JavaScript Stylechanger’, we need to add a few more lines to the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<script type="text/javascript">
window.onload = function() {
    document.getElementById('style1').onclick = function(evt) {changeStyle(1);};
    document.getElementById('style2').onclick = function(evt) {changeStyle(2);};
    document.getElementById('style3').onclick = function(evt) {changeStyle(3);};
    if (document.cookie != '') {
        myCookieArray = document.cookie.split("; ");
        myCookiePair = myCookieArray[0].split("=");
        stylenum = myCookiePair[1];
    }
    changeStyle(stylenum); 
}
function changeStyle(stylenum) {
    var switcher = document.getElementById('switcher');
    var head = document.getElementsByTagName('head')[0];
    if (switcher) {
        head.removeChild(switcher);
    }
    var link = document.createElement('link');
    link.setAttribute('id','switcher');
    link.setAttribute('rel','stylesheet');
    link.setAttribute('href','css/style' + stylenum + '.css');
    link.setAttribute('type','text/css');
    head.appendChild(link);
    document.cookie = "style=" + stylenum + ";max-age=" + (60*60*24*30);
}
</script>

There is however one problem with this script. It uses window.onload to initiate the script. This means it waits for all of the elements on the page (including images) to fully load before implementing the JavaScript. This in turn means that you may see a ‘flicker’ as the new stylesheet gets loaded. My example is particularly bad for this as it changes the width of the content (quite a drastic change). If you’re just changing the colour of certain elements, the flicker might not be so noticeable. There are workarounds for this, notably mozilla’s DOMContentLoaded but by far the easiest route to take is to use one of the many javascript libraries such as the wonderful mootools. This replaces:

1
2
window.onload = function() {
}

with

1
2
window.addEvent('domready', function() {
	});

You can see the final example here.

Feed IconFollow me on Twitter





Make ElanMan happy and be the first to comment.

Leave a Comment







XHTML: You can use the following tags in your comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">