783

I'm trying to set a cookie depending on which CSS file I choose in my HTML. I have a form with a list of options, and different CSS files as values. When I choose a file, it should be saved to a cookie for about a week. The next time you open your HTML file, it should be the previous file you've chosen.

JavaScript code:

function cssLayout() {
    document.getElementById("css").href = this.value;
}


function setCookie(){
    var date = new Date("Februari 10, 2013");
    var dateString = date.toGMTString();
    var cookieString = "Css=document.getElementById("css").href" + dateString;
    document.cookie = cookieString;
}

function getCookie(){
    alert(document.cookie);
}

HTML code:

<form>
    Select your css layout:<br>
    <select id="myList">
        <option value="style-1.css">CSS1</option>
        <option value="style-2.css">CSS2</option>  
        <option value="style-3.css">CSS3</option>
        <option value="style-4.css">CSS4</option>
    </select>
</form>
7
  • 11
    kaka = "Css=document.getElementById("css").href" + kakdatum; is a syntax error. Commented Jan 28, 2013 at 23:37
  • what i wonder is how to set cookie based on a choice. If i choose a specific css file, then i want that file to be saved and activated the next time i open the html file Commented Jan 28, 2013 at 23:41
  • @DrWooolie How about marking an answer correct so visitors to this question will find the best answer? The top answer clearly isn't the best. Commented May 12, 2014 at 20:00
  • Now (2017), some use cases make investigating the Web Storage API, as opposed to cookies, worthwile. Commented Aug 3, 2017 at 9:02
  • A concise but fully featured modern approach to get/set cookies over at the duplicate question: stackoverflow.com/a/48706852/87520 Commented Feb 19, 2018 at 9:32

4 Answers 4

1225

I find the following code to be much simpler than anything else:

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

Now, calling functions

setCookie('ppkcookie','testcookie',7);

var x = getCookie('ppkcookie');
if (x) {
    [do something with x]
}

Source - http://www.quirksmode.org/js/cookies.html

They updated the page today so everything in the page should be latest as of now.

Sign up to request clarification or add additional context in comments.

24 Comments

toGMTString() is deprecated - just FYI. Reference
This won't work if your cookie contains a semicolon.
Why so complex? Use date.setDate(date.getDate() + days); instead
The eraseCookie function didn't work for me (FireFox Developer Edition 66.0b4). Instead, I had to use the code from B T's answer: document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'.
Nice answer. While using semicolon(;) in cookie value I have got problem. So I refined some lines. Please update in your answer. From function setCookie(name,value,days) document.cookie = name + "=" + (encodeURIComponent(value) || "") + expires + "; path=/"; From function getCookie(name) if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length)); Use encodeURIComponent(), decodeURIComponent() in retutn statement;
|
463

These are much much better references than W3Schools (the most awful web reference ever made):

Examples derived from these references:

// Sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// Sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

// Remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'

The Mozilla reference even has a nice cookie library you can use.

10 Comments

The expires variable is obsolete although still supported by browsers. Use max-age instead!
It looks like IE8 and below do not support max-age, so expires is the safer choice. blogs.msdn.com/b/ieinternals/archive/2009/08/20/…
There's also a domain param you can set on cookies which is useful if you want to use a cookie across different sub domains on your site.
Dont work on Chrome. See here why: stackoverflow.com/questions/26349052/…
Note that the MDN reference page mentions nothing about expires being deprecated/obsolete. That's because it can, on occasion, serve a purpose not covered by max-age. The value of max-age must be a numerical value interpreted as an amount of seconds, while the expires value can be set to the special value Session which is not the same as max-age=0;.
|
43

Check JavaScript Cookies on W3Schools.com for setting and getting cookie values via JS.

Just use the setCookie and getCookie methods mentioned there.

So, the code will look something like:

<script>
function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function cssSelected() {
    var cssSelected = $('#myList')[0].value;
    if (cssSelected !== "select") {
        setCookie("selectedCSS", cssSelected, 3);
    }
}

$(document).ready(function() {
    $('#myList')[0].value = getCookie("selectedCSS");
})
</script>
<select id="myList" onchange="cssSelected();">
    <option value="select">--Select--</option>
    <option value="style-1.css">CSS1</option>
    <option value="style-2.css">CSS2</option>
    <option value="style-3.css">CSS3</option>
    <option value="style-4.css">CSS4</option>
</select>

9 Comments

@BT could you elaborate on what about the above code is out of date and misinformed?
@BT, I've yet to see a reference on w3schools that is out of date or contains incorrect information.
-1 for w3schools
I just checked our analytics, and 10% of our IE users still use IE8 or lower. So using 'max-age' is a pretty bad idea.
Stupidness!! +1 for the working example, I don't actually see a problem with w3schools,
|
36

I'm sure this question should have a more general answer with some reusable code that works with cookies as key-value pairs.

This snippet is taken from MDN and probably is trustable. This is UTF-safe object for work with cookies:

var docCookies = {
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

Mozilla has some tests to prove this works in all cases.

There is an alternative snippet here:

10 Comments

Just a word of warning @SandipPingle, the code provided in this answer is actually GPL licensed.
@MarcinHabuszewski thanks for pointing out. How can I use this code then(my app is not GPL licensed)?
@SandipPingle That's the "charm" of GPL, you can't (unless you turn your app GPL). This code is somewhat similar to a generic solution to the problem, so it begs for a question: can generic code actually be licensed (or is such license valid in case of generic code)? Try using different (non-GPLed) code to solve your problem.
GPL or not, I prefer code I can read.
setItem does not work for me. I tested it on chrome. the other methods work fine.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.