Electric Type

Multimedia

About Us

News

Help

Advanced JavaScript Tutorial
Lesson 2

by Thau!

Page 12 — More About Cookies

So far, you've learned how to set and read a basic cookie. Unfortunately, your basic cookie will get deleted automatically when a user quits out of the browser. Sometimes this is for the best. Since each domain, such as webmonkey.com, is allowed only 20 cookies on any user's machine, you don't want to waste space with cookies that aren't saved between browser sessions.

However, if you do want to save cookies on users' hard drives, you have to set an expiration date, which has to be in a special format called GMT. For example:

Mon, 27-Apr-1998 00:00:00 GMT
(This is the date on which Koko the gorilla had her AOL chat session.)

Getting the GMT right can be sort of a pain, especially when it comes to figuring out the day of the date. Is it a Monday? A Friday? To make things easier on you, JavaScript has a date method called toGMTString. Here's an easy way to set an expiration date to some distant time in the future:

var the_date = new Date("December 31, 2023");

var the_cookie_date = the_date.toGMTString();

Once you establish an expiration date for your cookie, you have to add this information before you set the cookie. Therefore, your cookie should look like this:


cookie_name=blah_blah;expires=date

Basically, you're just adding expires=date to the cookie string and separating the different cookie components with a semicolon.

Here's how to build a cookie that will last until the end of the Mayan calendar:

function setCookie()
{

    // get the information
    //
    var the_name = prompt("What's your name?","");
    var the_date = new Date("December 31, 2023");
    var the_cookie_date = the_date.toGMTString();

    // build and save the cookie
    //
    var the_cookie = "my_cookie=" + escape(the_name);
    the_cookie = the_cookie + ";expires=" + the_cookie_date;
    document.cookie = the_cookie;

}

At the end of all this, the_cookie will look something like this:

my_cookie=thau;expires=Fri, 31-Dec-2023 00:00:00 GMT

When this cookie is set, it will live on the user's hard drive until the expiration date.

The expiration date also allows you to delete cookies you don't want users to have any more. If you set the expiration date of a cookie to a time that's already passed, the cookie will be deleted from the cookie file.

In addition to name and expires, there are two other important cookies components that you'll need to know about: path and domain.

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.