cybercoded.com | Articles | Chocolate Chip Cookies + Automating NEW! |  back 

Introduction

I'll start by saying the code described below (Get_Cookie(), Set_Cookie() and Delete_Cookie()) is based on the public domain cookie code produced by Bill Dortch. However, I have made some small alterations to improve the performance of cookie retrieval.

This article describes how to use cookies to extend the previous article Automating NEW!. This functionality was requested :

I'd like to suggest an enhancement to your "automatic NEW!" function. I'd like to show a "NEW!" next to categories that are new since the last time the visitor was at that page. Your stuff + cookies.

Cookies are items of information that your browser stores on your computer in a special file or folder. It is also possible for servers to retrieve this information that the server has requested be stored.

JavaScript and Cookies

It is also possible to use cookies with JavaScript. There are three basic functions Get_Cookie(), Set_Cookie() and Delete_Cookie():

function Get_Cookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring                     
    (0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}

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

function Delete_Cookie(name,path,domain) {
    if (Get_Cookie(name)) document.cookie = name + "=" +
        ( (path) ? ";path=" + path : "") +
        ( (domain) ? ";domain=" + domain : "") +
        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

The cookies used in this article stores two dates, the date that you the user last accessed this site, and the previous value of this date, and a visit counter. It is used in the JavaScript listing page to indicate which articles have been added to the listing since your last visit.

Obviously, if you haven't visited before then it would be better to indicate which articles have been added in the last two weeks (i.e. a default date).

Psuedo Code

The JavaScript code required to do this can be described using the following psuedo-code:

  1. Get today's date
  2. Set expire date to 56 days from now
  3. Set default date to 14 days ago
  4. Attempt to get the cookie
  5. If the cookie does not already exist:

     

    1. Move default date to previous last visited date
    2. Move today's date to last visited date
    3. Move one to the counter
    4. Store cookie
    5. Return default date
  6. Else if the cookie already exists:

     

    1. Retrieve last visited date
    2. Retrieve previous last visited date
    3. Retrieve the visit counter
    4. If the last visited date is not equal to today's date:

       

      1. Move last visited date to previous last visited date
      2. Move today's date to last visited date
      3. Add one to the counter
      4. Update cookie with new expiry date
    5. Return previous last visited date

The use of previous last visited date ensures that if the user returns to the page on the same day then the items are still shown as new.

JavaScript code

Here is the code:

<script language = 'JavaScript'>
<!--

//place Get_Cookie(), Set_Cookie() and Delete_Cookie() code here

var visitCounter = 0;
var lastHereDate = getLastHere();

function getLastHere() {
    var todays_date = new Date();
    var expires_date = new Date(todays_date.getTime() +
    (14 * 86400000)); // 2 weeks from now
    var default_date = new Date(todays_date.getTime() -
    (14 * 86400000)); // 2 weeks ago
    var lastHere = Get_Cookie("lastHere");
    if (!lastHere) {
        var previous_date = ccyymmdd(default_date);
        var last_date = ccyymmdd(todays_date);
        visitCounter = 1;
        Set_Cookie("lastHere",last_date + previous_date + 
        '0001', expires_date);
        return default_date;
    }
    else {
        var last_date = lastHere.substring(0,8);
        var previous_date = lastHere.substring(8,16);
        visitCounter = lastHere.substring(16,20) * 1;
        if (ccyymmdd(todays_date) != last_date) {
            previous_date = last_date;
            last_date = ccyymmdd(todays_date);
            visitCounter +=1;
            if (visitCounter > 1000) visitCounter = 1; 
       //unlikely, but so was the millennium!
            Set_Cookie("lastHere",last_date + previous_date +
            display(visitCounter), expires_date);
        }
        return convert_date(previous_date);
    }
}

function y2k(number)    { return (number < 1000) ? number +
 1900 : number; }
function padout(number) { return (number < 10) ? '0' +
 number : number; }

function ccyymmdd(date) {
// returns a date in the ccyymmdd format
    return '' + (y2k(date.getYear())) + padout(date.getMonth
() + 1) + padout(date.getDate());
}

function display(count) {
// returns the count in the 9999 format
    return (count < 10) ? '000' + count : ( 
           (count < 100) ? '00' + count : ( 
           (count < 1000) ? '0' + count : count ) );
}

function convert_date(string) {
// converts a string in the format ccyymmdd to a date
    return date = new Date(string.substring(0,4),
(string.substring(4,6)-1),string.substring(6,8));
}

function check_if_new(then) {
// returns NEW! if the then date is greater or equal to the last date
     if (Date.UTC(y2k(then.getYear()),then.getMonth(),then.getDate(),
0,0,0) >=
         Date.UTC(y2k(lastHereDate.getYear()),lastHereDate.getMonth(),
lastHereDate.getDate(),0,0,0)) {
         document.write(' <font color=red>NEW!<\/font>');
     }
}

//-->
</script>

It is possible to save the three items of information as separate cookies, though some people would say that this is a bit excessive. Storing the information as one text string in the format ccyymmddccyymmdd9999 means that you need to access the data using the substring() method.

To allow for further extension in future the visitCounter is formatted so that it is always a four digit number (using leading zeros).

All that is then required is a call to check_if_new with two dates, the date of the item, and the lastHereDate:

<script language = 'JavaScript'><!--
check_if_new(convert_date('19970421'));
//--></script>

Where 19970421 is the 21st of April 1997.

References

Accessing cookies via JavaScript by Bill Dortch

Official HTTP Cookie Spec at Netscape

cybercoded.com | Articles | Chocolate Chip Cookies + Automating NEW! |  back

 

Menu

Home
Articles
FAQ's
Links
Tools
Blog Links
AJAXCoded Blog
CyberCoded.net
CyberCoder
CybersView

Applications

 

Questions, Comments
or Suggestions

Site Search
FAQ Search

AJAX Coded
CAAD @ CyberCoded.net


 


Copyright


Google
WWW CyberCoded.com
Provide Feedback on CyberCoded.com

Copyright © 1996-2008 CyberCoded.com, All Rights Reserved.
CyberCoded.com liability, trademark, document use and software licensing rules apply. Your interactions with this site are in accordance with our public privacy statements.
Website Hosted By: USNX

We recommend USNX for quality ASP Web Hosting