spacer
Yehuda Shiran January 10, 2002
Setting Cookies
Tips: January 2002

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs

One way to store and retrieve data on the client side is by using cookies. The cookie property is a member of the document object. You can store thousands of cookies per client. You can set a cookie with the following function (put it in your <HEAD> section):

  function setCookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
    document.cookie = curCookie;
  }
Where:

  • name - name of the cookie
  • value - value of the cookie
  • [expires] - expiration date of the cookie (defaults to end of current session)
  • [path] - path for which the cookie is valid (defaults to path of calling document)
  • [domain] - domain for which the cookie is valid (defaults to domain of calling document)
  • [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
  • * an argument defaults when it is assigned null as a placeholder
  • * a null placeholder is not required for trailing omitted arguments

Notice how we check for argument existence. For example:

  ((expires) ? "; expires=" + expires.toGMTString() : "")
The test is done by evaluating expires, by enclosing it in parentheses. If it exists, then we add the string "; expires=", and the value of expires.toGMTString(), to curCookie. Otherwise, if expires is not present, we add a blank string to curCookie.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint