Basics
Creating a Document
Head and Body Elements
Formatting Text
Creating Lists
Embedding Images
URLs Explained
Linking to Documents
Creating Tables
Forms Form Basics
Input and Textarea
Select Lists
Frames Framesets
The Frame Element
Nested Framesets
Targetting Frames
Inline Frames
Tips and Tricks Meta Tags
Transition Effects
HTML Generators Create a Document
Create a List
Create a Table
HTML
Basics
Implementing CSS
CSS Syntax
Pseudo Classes/Elements
CSS Classes
CSS Properties Font Properties
Color and Background
Text Properties
Border Properties
Margins and Padding
Size and Position
Tips and Tricks Menu Buttons
Special Effects
CSS
Basics
Running a Script
Variables
Expressions and Operators
Objects.Properties.Methods
The Date Object
Strings
Regular Expressions
Defining RegExp Patterns
Branches and Conditions
Loops
Arrays Array Basics
Array Methods
Sorting Arrays

User-Defined Functions
Cookies
Windows
Frames
Tips and Tricks Image Replacement
Using Includes
Form Validation
Debugging
JavaScript
Basics
Creating a Script
Running a Script
Variables
Expressions and Operators
Strings Strings Basics
Strings and Substrings
Replacing Substrings
Regular Expressions
Branches and Conditions
Loops
Arrays Array Basics
Array Functions
Sorting Arrays
User-Defined Functions
Include and Require
Uploading Files
File Functions
Session Variables
Tips and Tricks Page Templates
Form Reply Scripts
Form Validation
JavaScript to PHP
PHP
Basics
Create and Drop
Show and Describe
Insert, Update and Delete
Querying
Join Queries
Functions
Table Locking
PHP/MySQL Functions Accessing a Database
Querying with PHP
Create and Drop with PHP
Insert and Update with PHP
Frequently Used Functions MySQL
Basics
Layout and Navigation
Page Content Style
Web Page Copy
Graphics and Animation
HTML Forms
Accessibility
Legal Requirements
MySQL
JavaScriptBasicsRunning a ScriptVariablesExpressions and OperatorsObjects.Properties.MethodsThe Date ObjectStringsRegular ExpressionsDefining RegExp PatternsBranches and ConditionsLoopsArraysArray MethodsSorting ArraysUser-Defined FunctionsJavaScript CookiesCookiesWindowsFrames

Home > JavaScript > Cookiesprinter version

JavaScript Cookies

A JavaScript cookie is a small file (no greater than 4Kb) that holds data and is stored by the web browser on the user's machine.

Cookies can be created, read from, modified or deleted and provide a means of saving state, allowing data to be shared across web pages.

A cookie is a property of the Document object and accepts the following attributes.

  1. Name - the name of the cookie.
  2. Value - the data to be stored in the cookie.
  3. Expiry Date - how long the cookie is to persist.
  4. Path - a path that determines which web pages will have access to the cookie.
  5. Domain - the domain that the cookie is associated with.
  6. Secure - determines if cookie data is transmitted over an http or https connection.


Creating a Cookie

The syntax of cookie creation is shown below with all attributes displayed except secure, which isn't widely used.


Basic Example of Storing a Cookie
<script language="javascript" type="text/javascript">
    document.cookie = "mycookie=Hello; expires=31/7/2009 14:45:00; path=/; domain=mydomain.com;";
</script>


The code above creates a cookie that expires at 2.45pm on 31/7/2009 and stores the string "Hello". The cookie attributes are explained below.

The name attribute

In this case the name of the cookie is mycookie and is followed by = then the string to store. However cookies don't allow commas, semicolons or whitespace within the string.

Since you're quite likely to use these characters in a cookie then you should use the JavaScript escape() function when creating the cookie and the unescape() function when you read the cookie.

The expires attribute

This sets the expiry time and date of the cookie. If omitted then the cookie expires at the end of the browser session (i.e. when the browser is closed).

The path attribute

This determines the path to web pages that are allowed access to the cookie. For example if only web pages within the products directory should have access to the cookie then the path would be /products.

In the example above the path / means the cookie may be accessed by any web page or directory within the document root.

If omitted then the cookie can only be accessed by web pages in the same directory as the web page that created it or by pages within any subdirectories.

The domain attribute

Setting this allows the cookie to be accessed by any web page on the domain, even if it's held on a different server, as well as any subdomains.

If omitted then the cookie may only be accessed by web pages on the server from which the cookie was created.

Using the escape() Function

If the cookie value includes commas, semicolons or whitespace then use the escape() function and concatenation to construct the string.

The example below sets an expiry time and date and can be accessed by any web page in same directory as the script creating the cookie.

Example of Storing a Cookie Using escape()
<script language="javascript" type="text/javascript">
    document.cookie = "mycookie=" + escape("Hello World") + ";expires=31/7/2008 14:45:00";
</script>


Reading a Cookie

To read the contents of a cookie you read the cookie property. This returns a name value pair in the form name = value where name is the name of the cookie and the value is the cookie string.

If there is more than one cookie then the string is a list of name value pairs separated by semicolons.

The value returned does not include any of the attributes set when the cookie was created, such as expiry etc.

If you used the escape() function to write the cookie then use the unescape() function to read it.

Example of Reading a Cookie Using unescape()
<script language="javascript" type="text/javascript">
    document.cookie = "mycookie=" + escape("Hello World");
    x = unescape(document.cookie);

    // This prints out mycookie=Hello World
    document.write(x);
</script>


Normally when you create a cookie it's to contain multiple pieces of information separated by a delimiter such as a colon.

If this is the case then use JavaScript string methods to chop up the string into it's different fields.

Deleting a Cookie

To delete a cookie simply set the expiry date to a date in the past.

Example of Deleting a Cookie
<script language="javascript" type="text/javascript">
    document.cookie = "mycookie=" + escape("Hello World");

    // This will delete mycookie
    document.cookie = "mycookie=";expires=Wed, 02-Aug-2000 00:00:00 GMT";
</script>


Previous - JavaScript User-Defined Functions Previous - User-Defined Functions     Next - Windows Next - JavaScript Windows


Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2010 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2010
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
Tips and TricksImage ReplacementUsing IncludesForm ValidationDebugging
Got any JavaScript Tips?
Send me your tip and if it's suitable I'll put it on the site, credit it to you and add a link back to your site.
Recommended Reading
Javascript the definitive guide

Javascript and DHTML cookbook

Pro javascript techniques

simply javascript