How to use Cookies in JavaScript

1. Add the following two JavaScript functions to your page somewhere:


function setCookie(c_name, value)
{
    var exdays = 365;
    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);
        }
    }
}
The setCookie function takes a cookie name (the key) and a value to set in the cookie, it assumes a 365 day expiry, and escapes the value so that it can be saved in the browser cookie.

The getCookie function takes the cookie name, searches through the cookies on the page for that key and returns the appropriate value.
2. Now you can use the functions on a page:

<input type="button" value="Set Cookie to YES" onclick="setCookie('blah','YES'); updateDisplay();" /> 
<input type="button" value="Set Cookie to NO" onclick="setCookie('blah','NO'); updateDisplay();" /> 
<input type="button" value="Clear Cookie" onclick="setCookie('blah',''); updateDisplay();" />  

Current Cookie Value Is : <span id="currCookieVal"></span> 

<script>
    
    function updateDisplay()
    {
        var cookieVal = getCookie('blah');
        if (typeof (cookieVal) == "undefined") { cookieVal = "undefined"; }
        document.getElementById("currCookieVal").innerHTML = cookieVal;
    }

    window.onload = updateDisplay;

</script>

3. Here is the above code rendered to test:

Current Cookie Value Is :

On initial page load, if this is your first time here, the getCookie function returns undefined. if you click any of the buttons, the cookie is set - you can test this by reloading the page, closing and returning to this page etc. The cookie will persist for 365 days or until the user clears cookies.

And that is all there is! You can store whatever you like in the cookie.