Quick Search:
 
 JavaScript: Javascript Cookie functions Jump to:  
Category: >> JavaScript >> Javascript Cookie functions  

<< lastnext >>

Snippet Name: Javascript Cookie functions

Description: Simple examples of setting and getting cookies.

Comment: (none)

Language: JAVASCRIPT
Highlight Mode: JAVASCRIPT
Last Modified: February 27th, 2009

setCookie(NAME, value) 
getCookie(NAME) 
clearCookie(NAME) 
clearCookies() 
 
 
 
FUNCTION setCookie(NAME, value)
         {
         //If name is the empty string, it places a ; at the beginning
         //of document.cookie, causing clearCookies() to malfunction.
         IF(NAME != '')
            document.cookie = NAME + '=' + value;
         }
 
FUNCTION getCookie(NAME)
         {
         //Without this, it will return the first value 
         //in document.cookie when name is the empty string.
         IF(NAME == '')
            RETURN('');
 
         name_index = document.cookie.indexOf(NAME + '=');
 
         IF(name_index == -1)
            RETURN('');
 
         cookie_value =  document.cookie.substr(name_index + NAME.length + 1, 
                                                document.cookie.length);
 
         //All cookie name-value pairs end with a semi-colon, except the last one.
         end_of_cookie = cookie_value.indexOf(';');
         IF(end_of_cookie != -1)
            cookie_value = cookie_value.substr(0, end_of_cookie);
 
         //Restores all the blank spaces.
         space = cookie_value.indexOf('+');
         WHILE(space != -1)
              { 
              cookie_value = cookie_value.substr(0, space) + ' ' + 
              cookie_value.substr(space + 1, cookie_value.length);
 
              space = cookie_value.indexOf('+');
              }
 
         RETURN(cookie_value);
         }
 
FUNCTION clearCookie(NAME)
         {                  
         expires = NEW Date();
         expires.setYear(expires.getYear() - 1);
 
         document.cookie = NAME + '=null' + '; expires=' + expires;            
         }
 
FUNCTION clearCookies()
         {
         Cookies = document.cookie;
         Cookie = Cookies;
         expires = NEW Date();
         expires.setYear(expires.getYear() - 1);
 
         WHILE(Cookie.length > 0)
              {
              //All cookie name-value pairs end with a semi-colon, except the last one.
              Cookie = Cookies.substr(0, Cookies.indexOf(';'));
              Cookies = Cookies.substr(Cookies.indexOf(';') + 1, Cookies.length);
 
              IF(Cookie != '')
                 document.cookie = Cookie + '; expires=' + expires;
              ELSE
                 document.cookie = Cookies + '; expires=' + expires;                                         
              }                      
         }


 
   Home |    Search |    Code Library |    Sponsors |    Privacy |    Terms of Use |    Contact Us © 2003 - 2024 psoug.org