Using Cookies

The following are the library functions that were discussed in class on Tuesday. I will post ways to call them and use them sometime before class on Thursday as well as specific assignments to practice the use of cookies with.

Code to be inserted in the header of the page


function setCookie (name, value, expires) {
        if (!expires) expires = new Date();
	document.cookie = name + "=" + escape (value) + 
	"; expires=" + expires.toGMTString() ;
}

==================

function delCookie (name) {
	var expireNow = new Date();
	document.cookie = name + "=" +
	"; expires="+ expireNow.toGMTString();
}

===================
//comments in the following function refer to the line immediately above the comment
function getCookie (name) {
	var dcookie = document.cookie; 	
//puts the cookie into a string called dcookie
	var cname = name + "=";		
// sets cname to the name of the cookie followed by an =
	var clen = dcookie.length;		
// sets clen = the length of the cookie
	var cbegin = 0;	
        while (cbegin < clen) {			
// as long as there's still somewhere to look in the cookie
        var vbegin = cbegin + cname.length;	
// vbegin is the place where the value should begin
                if (dcookie.substring(cbegin, vbegin) == cname) {   
// this looks for the name of the cookie within the string between positions cbegin and vbegin
                var vend = dcookie.indexOf (";", vbegin);	
// sets the end of the value at the location of the first semi-colon following vbegin
                        if (vend == -1) vend = clen;		
// if this was the last cookie the semi-colon would be missing so use the end of the cookie instead
                return unescape(dcookie.substring(vbegin, vend));	
// this sends the value back and simultaneously exits from the function
                }
// end of the if statement
        cbegin = dcookie.indexOf(" ", cbegin) + 1;
//moves cbegin up to the position following the next blank space to continue looking
                if (cbegin == 0) break;
// if  no spaces were found then exit the while loop
        }
return null;
// return nothing since the cookie wasn't found.
//NOTE: if it had been found the return 11 lines up would have  sent the value back when the function was exited
}