PDA

View Full Version : Javascript Cookie



stuu
14 Aug 2006, 11:13 AM
Hi all,

Right I'm developing a page at the moment, let's say for fun, that uses some of the new Yahoo UI stuff. I have a login "box" that the user can choose to hide if they want to. When they click the close icon, it nicely animates to a closed or hidden position. Click again and it slides open. Nice. Doesn't work in IE but i've catered for that.

What i need to do is write a cookie that will remember the user's choice each time the page is refreshed, otherwise it's kind of pointless. I've never written a cookie before and am a bit simple in the ways of Javascript. Any ideas what i need to do?

I'm guessing i need to find the relevant id and it's state and then record it in the cookie. But how?

Many thanks.

ajlozier
14 Aug 2006, 03:19 PM
interesting question. you inspired me to look it up myself! :)

the functions you are going to need are 1) one that loads at the beginning of your page and checks the value on the cookie. and 2) the one that changes the value of the cookie whenever the event is triggered. (onclick="function();")

cookies are stored as a long string containing all the cookie values for that page. the format of the string is "cookiename=cookievalue;expires = Mon, 31 Dec 2040 23:59:59 GMT;" and every cookie you add, adds to the string.

since it sounds like you are talking about an on/off situation, i might call the cookie toggle and set its value at 0 or 1.

you have to parse through the cookie string to find the variable you want, using a function like this:

function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}

// a cookie with the requested name does not exist
return null;
}

so your init function might look something like this:

init()
{
if (GetCookie('toggle') == 1)
{
// open the tabl
}
else
{
// keep it closed
}
}

when someone triggers the event, you will need to call a function like this:

function SetToggle(onoff)
{
date = new Date();
document.cookie = "toggle=" + escape(onoff) + "; expires=" + date.toGMTString();
}

where onoff is a one or a zero, depending on whether you are toggling on or off.

this is about as much detail as i can go into without getting into your actual code. i'd be happy to offer additional tips as you work on this a bit more. hope this helped!

aaron lozier
informationarchitech.com
Louisiana Web Design (http://www.informationarchitech.com)