web blazonry web development scripts and tutorials
 
Web blazonry.com
   Home       PHP       Name Generators       Perl       CSS       Javascript       Java       devTips       Resources   

Javascript Home


image scripts
  Image Load Order
  Mouse Overs
  SlideShow

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





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:

//-->
</script>

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:

<form>
<input type="button" value="Set a Cookie" onClick="setCookie('myCookie','it is crunchy', exp)">
</form>
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
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
Source Code for Test Google Ads (PHP)
Most Popular Pages
U.S. Name Generator
Wu Name Generator
Baby Name Generator
Upload and Resize an Image (PHP)
Popup Windows (JavaScript)
How To Install Apache + PHP + MySQL
Simple Web Calendar (PHP)

Least Popular Pages
Image Load-Order (Javascript)
dHTML: Scrolling Layers
iNews Aplet (Java)
ProcLog Search Your Logs (Perl)
 
 

  © 1997-2008. astonishinc.com   All Rights Reserved.