• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / JavaScript / JavaScript and Cookies

JavaScript and Cookies

31 October 2002 / 9 Comments

A great feature of JavaScript is that it lets you set and retrieve browser cookies. In this tutorial I’ll show you how this is done, along with a simple example that remembers your name and displays it on every page.

What are cookies?

Cookies are small amounts of data stored by the web browser. They allow you to store particular information about a user and retrieve it every time they visit your pages. Each user has their own unique set of cookies.

Cookies are typically used by web servers to perform functions such as tracking your visits to websites, enabling you to log in to sites, and storing your shopping cart. However we don’t need fancy web server programming to use cookies. We can use them in JavaScript, too!

The document.cookie property

Cookies in JavaScript are accessed using the cookie property of the document object. In simple terms, we create a cookie like this:


document.cookie = "name=value; expires=date; path=path;
                   domain=domain; secure";

…and retrieve all our previously set cookies like this:


var x = document.cookie;

Let’s look more closely at how to set and retrieve cookies.

Setting a cookie

To set a cookie, we set the document.cookie property to a string containing the properties of the cookie that we want to create:


document.cookie = "name=value; expires=date; path=path;
                   domain=domain; secure";

These properties are explained in the table below:

Property Description Example
name=value This sets both the cookie’s name and its value. username=matt
expires=date This optional value sets the date that the cookie will expire on. The date should be in the format returned by the toGMTString() method of the Date object. If the expires value is not given, the cookie will be destroyed the moment the browser is closed. expires=
13/06/2003Β 00:00:00
path=path This optional value specifies a path within the site to which the cookie applies. Only documents in this path will be able to retrieve the cookie. Usually this is left blank, meaning that only the path that set the cookie can retrieve it. path=/tutorials/
domain=domain This optional value specifies a domain within which the cookie applies. Only websites in this domain will be able to retrieve the cookie. Usually this is left blank, meaning that only the domain that set the cookie can retrieve it. domain=elated.com
secure This optional flag indicates that the browser should use SSL when sending the cookie to the server. This flag is rarely used. secure

Let’s look at a few examples of cookie setting:


document.cookie = "username=John;
                  expires=15/02/2003 00:00:00";

This code sets a cookie called username, with a value of "John", that expires on Feb 15th, 2003 (note the European time format!).


var cookie_date = new Date ( 2003, 01, 15 );
document.cookie = "username=John;
                  expires=" + cookie_date.toGMTString();

This code does exactly the same thing as the previous example, but specifies the date using the Date.toGMTString() method instead. Note that months in the Date object start from zero, so February is 01.


document.cookie = "logged_in=yes";

This code sets a cookie called logged_in, with a value of "yes". As the expires attribute has not been set, the cookie will expire when the browser is closed down.


var cookie_date = new Date ( );  // current date & time
cookie_date.setTime ( cookie_date.getTime() - 1 );
document.cookie = "logged_in=;
                  expires=" + cookie_date.toGMTString();

This code sets the logged_in cookie to have an expiry date one second before the current time – this instantly expires the cookie. A handy way to delete cookies!

There’s no escape!

Strictly speaking, we should be escaping our cookie values — encoding non-alphanumeric characters such as spaces and semicolons. This is to ensure that our browser can interpret the values properly. Fortunately this is easy to do with JavaScript’s escape() function. For example:


document.cookie = "username=" + escape("John Smith")
                  + "; expires=15/02/2003 00:00:00";

A function to set a cookie

Setting cookies will be a lot easier if we can write a simple function to do stuff like escape the cookie values and build the document.cookie string. Here’s one we prepared earlier!


function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );
  
  if ( secure )
        cookie_string += "; secure";
  
  document.cookie = cookie_string;
}

This function expects the cookie data to be passed to it as arguments; it then builds the appropriate cookie string and sets the cookie.

For example, to use this function to set a cookie with no expiry date:


set_cookie ( "username", "John Smith" );

To set a cookie with an expiry date of 15 Feb 2003:


set_cookie ( "username", "John Smith", 2003, 01, 15 );

To set a secure cookie with an expiry date and a domain of elated.com, but no path:


set_cookie ( "username", "John Smith", 2003, 01, 15, "",
             "elated.com", "secure" );

Feel free to use this function in your own scripts! πŸ™‚

A function to delete a cookie

Another useful cookie-handling function is provided below. This function will “delete” the supplied cookie from the browser by setting the cookie’s expiry date to one second in the past.


function delete_cookie ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

To use this function, just pass in the name of the cookie you would like to delete – for example:


delete_cookie ( "username" );

Again, you can use this function in your own scripts if you like. πŸ™‚

Retrieving cookies

To retrieve all previously set cookies for the current document, you again use the document.cookie property:


var x = document.cookie;

This returns a string comprising a list of name/value pairs, separated by semi-colons, for all the cookies that are valid for the current document. For example:


"username=John; password=abc123"

In this example, 2 cookies have been previously set: username, with a value of "John", and password, with a value of "abc123".

A function to retrieve a cookie

Usually we only want to read the value of one cookie at a time, so a string containing all our cookies is not that helpful! So here’s another useful function that parses the document.cookies string, and returns just the cookie we’re interested in:


function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

The function uses a regular expression to find the cookie name and value we’re interested in, then returns the value portion of the match, passing it through the unescape() function to convert any escaped characters back to normal. (If it doesn’t find the cookie, it returns a null value.)

Using the function is easy. For example, to retrieve the value of the username cookie:


var x = get_cookie ( "username" );

Again, feel free to use this function with your own JavaScript code!

A simple example

In this example, we’ve created a page that prompts you for your name the first time you visit it, then stores your name in a cookie and displays your name in the page on subsequent visits.

Open the page in a new window. The first time you visit the page, it should ask you for your name and store it in a cookie. If you visit the page again at any point, it will get your name from the cookie and display it within the page.

Try closing the window that pops up, then opening it again in a new window. Notice that this time it still displays the user name that it retrieved from the cookie!

The cookie is given an expiry date of 1 year from the current date, which means that the browser will remember your name even if you close it down and re-open it.

You can clear the cookie by clicking on the Forget about me! link, which calls our delete_cookie() function and then refreshes the page to prompt you for a name again.

You can view all the JavaScript source for the example page by switching to the other browser window now and using the View Source option in your browser. Here’s the main part of the code:


if ( ! get_cookie ( "username" ) )
{
  var username = prompt ( "Please enter your name", "" );

  if ( username )
  {
    var current_date = new Date;
    var cookie_year = current_date.getFullYear ( ) + 1;
    var cookie_month = current_date.getMonth ( );
    var cookie_day = current_date.getDate ( );
    set_cookie ( "username", username, cookie_year, cookie_month, cookie_day );
  }
}
else
{
  var username = get_cookie ( "username" );
  document.write ( "Hi " + username + ", welcome to my website!" );
  document.write ( "<br><a href=\"javascript:delete_cookie('username');
                    document.location.reload ( );\">
                    Forget about me!</a>" );
}

Notice how the function uses our get_cookie(), set_cookie() and delete_cookie() library functions to do the hard work!

This tutorial has shown you how to use cookies in JavaScript to store information about your visitors. You can use the supplied functions in your own scripts to set, retrieve and delete cookies easily. Enjoy! πŸ™‚

Filed Under: JavaScript Tagged With: browser cookies, java script, programming, scripting, web development

Reader Interactions

Comments

  1. Kiko says

    4 February 2011 at 12:33 pm

    Hi, i have autolike script, i need to add cookies to activate the script only ones for each visitor that click the like. how can i add cookies to this script. thanks

    Reply
  2. matt says

    4 February 2011 at 5:40 pm

    Please post your question in a new topic:

    http://www.elated.com/forums/authoring-and-programming/topic/new/

    Reply
  3. cheapchop says

    19 September 2011 at 1:15 pm

    I see that this article was originally posted on Halloween of 2002, but have you been modifying this article as time goes by? Maybe js cookie functionality hasn’t changed much since 2002, but do you generally update your articles when syntax changes or newer functionality is offered by browsers? i like elated, thanks πŸ™‚

    Reply
  4. matt says

    23 September 2011 at 2:31 am

    @cheapchop: Thanks for your comment! We don’t generally update articles, except in special circumstances. We prefer instead to create new articles on the topic if it’s changed a lot.

    I don’t believe JS’s cookie handling has changed much since the article was written.

    Reply
  5. Angry Black Man says

    7 April 2012 at 9:55 am

    https://developer.mozilla.org/en/DOM/window.escape

    “escape” is not part of any officially recognized DOM standard. this tutorial should certainly be updated to use recognized DOM methods.

    aside from that, this is a GREAT tutorial.

    [Edited by Angry Black Man on 07-Apr-12 09:55]

    Reply
  6. chrishirst says

    9 April 2012 at 2:52 pm

    window.escape????

    Are you reading the same article as the rest of us?

    escape() is a javascript METHOD/function for encoding special characters for use in URLs or in a HTTP request.
    http://www.w3schools.com/jsref/jsref_escape.asp

    It is not even used in the article as in it were part of the DOM specification.

    Reply
  7. Angry Black Man says

    9 April 2012 at 4:06 pm

    Hi Chris,

    “escape()”

    is the same thing as

    “window.escape()”

    a lot of people are confused by this as you are. it’s understandable. there are no “free standing” functions in javascript. all functions are attached to some object in some way in the DOM. everything in javascript is located within the DOM. everything.

    the reason i mentioned escape was because of cheapchop’s comments and the response he received by matt in which he declared that “I don’t believe JS’s cookie handling has changed much since the article was written”. “much” is a subjective term, but in the interests of modern browser compatibility, this is certainly a valid, useful observation that would do well to be incorporated into an article like this.

    Reply
  8. chrishirst says

    10 April 2012 at 8:45 am

    “”escape()”

    is the same thing as

    “window.escape()” ”

    No it is NOT! Maybe you don’t quite understand the fundamentals of OOP.

    window.name would refer to a property or method that is a member of (or belongs to) an object class, in this case the “window” object. Just as math.floor() is a member method of the math object.

    escape() is a GLOBAL method/function that does NOT rely on the Document Object Model at all, it is part of the javascript interpreter.
    The list of Global properties and methods are at -> http://www.w3schools.com/jsref/jsref_obj_global.asp and a list of member properties and methods of the window object is at -> http://www.w3schools.com/jsref/obj_window.asp

    If escape() was a member of any object, it should/would belong to the string object, as it operates on a string of characters.

    Reply
  9. punktobbe says

    19 March 2014 at 2:58 pm

    In javascript there is always a global object. In browsers this global object is the same as the window object. So actually:

    escape === window.escape // -> true
    

    However, the escape function is not part of the DOM, it is pure javascript and a property of the global object.

    http://www.ecma-international.org/ecma-262/5.1/#sec-B.2.1

    [Edited by punktobbe on 19-Mar-14 14:59]

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits