Paul McFedries' Web Home


Setting a Cookie in JavaScript

This page demonstrates how to use JavaScript to set a simple
cookie on the user's machine. To try it out, enter a name in
the box below and then click the Set the Cookie button.
The script stores the name in a cookie file on the user's
machine, loads a new page, and then displays the name in an
alert box.

Type in your name:

Here's the JavaScript that performs all of this:

<SCRIPT LANGUAGE = "JavaScript">
<!--
    // This function gets things set up, creates the cookie,
    // and then moves to the next page
    //
    function BakeIt() {
        // Get the value of the "data" field in the form
        var cookieData = document.cookieForm.data.value;

        // See if the data was entered
        if (cookieData != null) {

            // Use this variable to set the name of the cookie
            var cookieName = "Name";

            // Use this variable to set the number of days after which the cookie will expire
            var days = 1;

            // Calculate the expiration date
            var expires = new Date ();
            expires.setTime(expires.getTime() + days * (24 * 60 * 60 * 1000)); 

            // Set the cookie
            SetCookie(cookieName, cookieData, expires);
        }

        // Move to the next Cookies page
        // Note that this is optional; you can delete this line if you want
        window.location = "cookies2.asp";
    }

    function SetCookie(cookieName, cookieData, expireDate) {
        document.cookie = cookieName + "=" + escape(cookieData) + "; expires=" + expireDate.toGMTString();
    }    
//-->
</SCRIPT>
To use this script, you need to do the following:
  1. Copy everything between and including the <SCRIPT> and
    </SCRIPT> tags and place it between the </HEAD> and
    <BODY> tags on your page.
  2. Set up a form on your page and set the NAME attribute of the
    field to data.
  3. Modify the following line in the script to set the name you
    want to use for the cookie:
    var cookieName = "Name";
    
  4. Modify the following line in the script to set the number of
    days after which the cookie should expire:
    var days = 1;
    
  5. Modify (or delete) the following line in the script to set the next page
    to display:
    window.location = "cookies2.asp";
    

    Copyright © 1995-2008 Paul McFedries and Logophilia Limited