To create a cookie in JavaScript you must assign a string to document.cookie
.
It takes values in a name = value
format e.g.
document.cookie = 'data=hello; max-age=60; path=/; domain=yoursite.com';
The best way to store an array in here is to use JSON and the method JSON.stringify():
var arr = ['hello', 'goodbye', 'au revoir'];
document.cookie = 'data=' + escape(JSON.stringify(arr)) + '; max-age=60; path=/; domain=yoursite.com'
(Note a cookie must be <= 4KB)
Retrieving the cookie is a little harder as it is a string, so I borrowed this function which searches the string for your cookie name then returns it's value:
// Source: http://www.thesitewizard.com/javascripts/cookies.shtml
function get_cookie ( cookie_name )
{
var cookie_string = document.cookie ;
if (cookie_string.length != 0) {
var cookie_value = cookie_string.match (
'(^|;)[\s]*' +
cookie_name +
'=([^;]*)' );
return decodeURIComponent ( cookie_value[2] ) ;
}
return '' ;
}
In our example you would use it like this:
var cookie = get_cookie('data');
var arr = JSON.parse(cookie); // Convert JSON string back into array
Note I use JSON.parse() to convert the JSON string back into a JavaScript array.
For more information on utilising cookies in JavaScript I suggest you read: http://www.thesitewizard.com/javascripts/cookies.shtml