JavaScript Cookies

|  | Search W3Schools : |

HOME | HTML | CSS | XML | JAVASCRIPT | ASP | PHP | SQL | MORE... |  | References | Examples | Forum | About

ADVERTISEMENTS XML Certification Download XML editor Custom Programming |  |

Table of contents

JS Basic
JS HOME
JS Introduction
JS How To
JS Where To
JS Statements
JS Comments
JS Variables
JS Operators
JS Comparisons
JS If...Else
JS Switch
JS Popup Boxes
JS Functions
JS For Loop
JS While Loop
JS Break Loops
JS For...In
JS Events
JS Try...Catch
JS Throw
JS onerror
JS Special Text
JS Guidelines
JS Objects
JS Objects Intro
JS String
JS Date
JS Array
JS Boolean
JS Math
JS RegExp
JS HTML DOM
JS Advanced
JS Browser
JS Cookies
JS Validation
JS Animation
JS Image Maps
JS Timing
JS Create Object
JS Summary
Examples/Quiz
JS Examples
JS Object Examples
JS DOM Examples
JS Quiz
JS Exam
JS References
JS Objects
JS HTML DOM

Selected Reading

Web Statistics
Web Glossary
Web Hosting
Web Quality
W3Schools Tutorials
W3Schools Forum
Helping W3Schools

# JavaScript Cookies

A cookie is often used to identify a user.

## Examples

Create a welcome cookie

## What is a Cookie?

A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.

Examples of cookies:

- Name cookie - The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like "Welcome John Doe!" The name is retrieved from the stored cookie
- Password cookie - The first time a visitor arrives to your web page, he or she must fill in a password. The password is then stored in a cookie. Next time the visitor arrives at your page, the password is retrieved from the cookie
- Date cookie - The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday August 11, 2005!" The date is retrieved from the stored cookie

## Create and Store a Cookie

In this example we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web page, he or she will be asked to fill in her/his name. The name is then stored in a cookie. The next time the visitor arrives at the same page, he or she will get welcome message.

First, we create a function that stores the name of the visitor in a cookie variable:

    function setCookie(c_name,value,expiredays)
    {
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
    }

The parameters of the function above hold the name of the cookie, the value of the cookie, and the number of days until the cookie expires.

In the function above we first convert the number of days to a valid date, then we add the number of days until the cookie should expire. After that we store the cookie name, cookie value and the expiration date in the document.cookie object.

Then, we create another function that checks if the cookie has been set:

    function getCookie(c_name)
    {
    if (document.cookie.length>0)
      {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start!=-1)
        {
        c_start=c_start + c_name.length+1;
        c_end=document.cookie.indexOf(";",c_start);
        if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
        }
      }
    return "";
    }

The function above first checks if a cookie is stored at all in the document.cookie object. If the document.cookie object holds some cookies, then check to see if our specific cookie is stored. If our cookie is found, then return the value, if not - return an empty string.

Last, we create the function that displays a welcome message if the cookie is set, and if the cookie is not set it will display a prompt box, asking for the name of the user:

    function checkCookie()
    {
    username=getCookie('username');
    if (username!=null && username!="")
    {
    alert('Welcome again '+username+'!');
    }
    else
    {
    username=prompt('Please enter your name:',"");
    if (username!=null && username!="")
    {
    setCookie('username',username,365);
    }
    }
    }

All together now:

    <html>
    <head>
    <script type="text/javascript">
    function getCookie(c_name)
    {
    if (document.cookie.length>0)
      {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start!=-1)
        {
        c_start=c_start + c_name.length+1;
        c_end=document.cookie.indexOf(";",c_start);
        if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
        }
      }
    return "";
    }

    function setCookie(c_name,value,expiredays)
    {
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
    }

    function checkCookie()
    {
    username=getCookie('username');
    if (username!=null && username!="")
      {
      alert('Welcome again '+username+'!');
      }
      else
      {
      username=prompt('Please enter your name:',"");
      if (username!=null && username!="")
        {
        setCookie('username',username,365);
        }
      }
    }
    </script>
    </head>

    <body onLoad="checkCookie()">
    </body>
    </html>

The example above runs the checkCookie() function when the page loads.

## Get Your Diploma!

W3Schools' Online Certification Program is the perfect solution for busy professionals who need to balance work, family, and career building.

The HTML Certificate is for developers who want to document their knowledge of HTML, XHTML, and CSS.

The JavaScript Certificate is for developers who want to document their knowledge of JavaScript and the HTML DOM.

The XML Certificate is for developers who want to document their knowledge of XML, XML DOM and XSLT.

The ASP Certificate is for developers who want to document their knowledge of ASP, SQL, and ADO.

The PHP Certificate is for developers who want to document their knowledge of PHP and SQL (MySQL).

WEB HOSTING
ASP.NET Web Hosting
$15 Domain Name Registration Save $20 / year!
Buy UK Domain Names Register Domain Names
Cheap Domain Names Cheap Web Hosting
Best Web Hosting
PHP MySQL Hosting
Top 10 Web Hosting
UK Reseller Hosting
Web Hosting
FREE Web Hosting

WEB BUILDING
Website Templates Flash Templates Website Builder Internet Business Opportunity
Custom Programming
FREE Trial or Demo Web Content Manager Forms,Web Alerts,RSS
Download XML editor
FREE Flash Website
FREE Web Templates

EDUCATION
US Web Design Schools
HTML Certification
JavaScript Certification
XML Certification
PHP Certification
ASP Certification

HOME or Top of Page |  | Printer Friendly
W3Schools is for training only. We do not warrant the correctness of its content. The risk from using it lies entirely with the user. While using this site, you agree to have read and accepted our terms of use and privacy policy. Copyright 1999-2009 by Refsnes Data. All Rights Reserved.