Electric Type

Multimedia

About Us

News

Help

Advanced JavaScript Tutorial
Lesson 2

by Thau!

Page 11 — Reading and Writing Multiple Cookies

On the last page, we learned how to cram lots of information into one cookie. Another way to do this is with multiple cookies.

Saving multiple cookies is very straightforward. We've learned that every cookie has a name. In the last example, we named the cookie my_happy_cookie, and did something like this:

var the_cookie = "my_happy_cookie=happiness_and_joy";

document.cookie = the_cookie;

To save multiple cookies, just give each cookie a different name. If you're adding a new cookie, setting document.cookie doesn't delete cookies that are already there. So if we do this:

var the_cookie = "my_happy_cookie=happiness_and_joy";

document.cookie = the_cookie;

var another_cookie= "my_other_cookie=more_joy_more_happiness";

document.cookie = another_cookie;
You'll now have access to both cookies. It's sort of weird, so make sure you understand what's going on.

Let's assume you executed the last block of code and you want to access my_happy_cookie. If you look at document.cookie, you'll see this:

my_happy_cookie=happiness_and_joy;

my_other_cookie=more_joy_more_happiness;
If you don't believe me, just look at your cookie.

function WM_readCookie(name) {

	if (document.cookie == '') { 
    
   // there's no cookie, so go no further
    
	return false;

	} else {
    
   // there is a cookie

	var firstChar, lastChar;

	var theBigCookie = document.cookie;

	firstChar = theBigCookie.indexOf(name);
	
   // find the start of 'name'

	if(firstChar != -1)  {
	
   // if you found the cookie

	firstChar += name.length + 1;
	    
   // skip 'name' and '='
	   
	lastChar = theBigCookie.indexOf(';', firstChar);
	    
   // Find the end of the value string (i.e. the next ';').
	    
	if(lastChar == -1) lastChar = theBigCookie.length;
	    
	return unescape(theBigCookie.substring(firstChar, lastChar));

	} else {
	
   // If there was no cookie of that name, return false.
	
	return false;
	
	}

    }
}

// WM_readCookie

Since this is very well commented, I'll just let you take a look at it and figure out what's happening on your own (c'mon, you know everything you need to know to make sense of this).

Once you've parsed that information, let's leave our "setting and reading basic cookies" discussion and look at some of the cooler things you can do with cookies.

next page»


Tutorials  

User Blogs  

Teaching Tools  

Authoring  

Design  

Programming help  

Advanced Flash  

Javascript  

Glossary  

PHP Coding  

User Blogs

Screen Shots

Latest Updates

Contact Us

Valid HTML 4.01!
Valid CSS!

Breadcrumb

© ElectricType
Maintained by My-Hosts.com
Site map | Copyright | Disclaimer
Privacy policy | Acceptable Use Policy
Legal information.