web blazonry web development scripts and tutorials Get best price on Prepaid Samsung Galaxy A01
   PHP       Name Generators       Perl       CSS       Javascript       Java       MySql       How Tos       Resources   

Javascript Home

image scripts
  Image Load Order
  Mouse Overs

JavaScript Resources
  Free JavaScript Books(new)
  Recommended Sites
  Bestselling Books

Bookmark and Share

JavaScript: How to Work With Cookies (Part 2)

Saving a Cookie

Use the setCookie JavaScript function to create a cookie and save a value to that cookie. Pass it three things: name, value and expires.

The name is the name of the cookie you set. We will use it also when retrieving the cookie.

The value is the information you want the cookie to save. Cookies don’t like spaces, semi-colons, or commas, so we use the function escape(value) to encode the value. We will “un-escape” the value when retrieving the cookie.

expires is when the cookie will expire (when it is be deleted from the user’s computer). It is optional. If not used, the cookie expires when the user exits.

The expiration date is the only tricky part. We create a new Date object. The expiration date is stored in milliseconds. An expiration date of x days in the future requires converting the x days to milliseconds in order to add them together.

Putting together a basic setCookie function is quite easy.

<script language="JavaScript"><!--
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());

Now, make the new Date object and set it 30 days ahead:

var exp = new Date();     //set new date object
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));     //set it 30 days ahead

Remember to close the script tag:


So we can see it work, let’s set our cookie with a button.

We just set a cookie with the name myCookie and the value it is crunchy Here is the HTML for the button and setting the cookie:

<input type="button" value="Set a Cookie" onClick="setCookie('myCookie','it is crunchy', exp)">
Note: the input tag is one line

Next >> Retrieving a Cookie


Related Links:

    Cookie Central -- a site devoted completely to information about cookies.


Newest Pages
Test Google Ads Ver. 2
Free Linux Admin Books
Free Linux Books for Programmers
Free Books for Linux on the Desktop
Free PHP Books
Free JavaScript Books
Free Java Books - Advanced
Free Java Books - Basic
Free Perl Books
Free Python Books
Quote of the Day (PHP)
Debugging Part 2
How to Test Google Ads
Most Popular Pages
Baby Name Generator
U.S. Name Generator
Wu Name Generator
Popup Windows (JavaScript)
Upload and Resize an Image (PHP)
How To Install Apache + PHP + MySQL
Intro to Web Databases (PHP, MySQL)

Least Popular Pages
iNews Applet (Java)
Java Resources
Site Monitor (Perl)
PHP Resources

  privacy policy     ||     © 1997-2016. astonishinc.com   All Rights Reserved.