[JavaScript] Cookies

A Cookie is a piece of text data stored by the browser on the user’s computer. Cookies have a name, a value, and a expire date. You need some work to save and retrieve cookies when you use JavaScript. You can find jQuery plugins for easier use.  

1. Saving Cookies

You can save a cookie into the “cookie” property of the “document” object. You can access the “document” object through the “Window” object, which you can omit in the code. You need to specify several pieces of data separated by a semicolon (‘;’).

The basic syntax is

document.cookie = “name = value; expires=…; path=/”;

You can use the following function to save a cookie.

function writeCookie(name, value, days) {
  if (!days) {
    days = 7;   // default, a week
  var date = new Date();
  date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  var expire = date.toUTCString();

  var cookie = name + '=' + value + ';expires=' + expire + '; path=/';
  document.cookie = cookie;


2. Reading Cookies

Cookies are saved into a big chunk, so you need to split each cookie and find the specified name.

function readCookie(name) {
  var cookies = document.cookie.split(';');
  for (var i = 0; i < cookies.length; i++) {
    var cookie = jQuery.trim(cookies[i]);
    if (cookie.indexOf(name + '=') == 0) {
      return cookie.substring(name.length + 1);
  return null;


3. Deleting Cookies

There’s no direct way to delete a cookie from a list. But by setting the expiration date earlier than today, you can expire the cookie.

function eraseCookie(name) {
  writeCookie(name, '', -1);


4. Example

Let’s save your name and remember it when the page is reloaded.


$(document).ready(function () {
  $('#save').click(function () {
    writeCookie('myname', $('#name').val(), 30);
  $('#erase').click(function () {
  $('#reload').click(function () {
  var nameFromCookie = readCookie('myname');
  if (nameFromCookie) {


5. Checking if Cookie is Enabled

Users can disable cookies in their browsers in many reasons. JavaScript provides an easy way to test whether cookies are enabled in the browser.

The “Navigator” object has the boolean “cookieEnabled” property. The “Navigator” object is accessible by the “navigator” property of a “Window” object.

if (navigator.cookieEnabled) {
  alert('Cookie is enabled');
} else {
  alert('Cookie is disabled');

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s