I was asked in a comment about a bit of javascript I used on DealCrew.com. Since I didn’t do anything too interesting in developing the site I figured this was as good as anything to write about.

The javascript is pretty basic, but the idea is fairly creative…although I can’t take credit for it, as I’ll explain below. The javascript simply reads a cookie and changes the css class for elements that are new since the user’s last visit. The huge advantage to this is being able to cache the page, yet still allow it to be custom for each user.

A couple caveats before I begin: 1. The javascript code used was inspired heavily by the code used at Original Signal…that is to say I took the code and modified it slightly. Which brings me to caveat #2: My modifications may have broken the code by adding inconsistencies depending on the users time zone.

On to the code:


function mark_new() {
  //get the current time in milliseconds since January 1, 1970
  stamp = new Date().getTime();

  //get the time of the users last visit or 0 if this is their first visit
  last_visit = getCookie('last_visit');
  if(last_visit == null || last_visit == 0) {
    last_visit = 0;
  }

  classes = document.getElementsByClassName('item');
  classes.each(function(link) {
    if(link.rel > last_visit) {
      link.className = "new";
    }
  });

  //set a cookie to time of this visit, converting to seconds from milliseconds
  setCookie('last_visit', Math.ceil(stamp / 1000));
}

Check out the full code for the getCookie/setCookie functions. They do pretty much what you would guess they do.

The interesting bit is the loop through the elements with the class “item”. The first thing you’ll notice is that the getElementsByClassName function isn’t standard javascript. You’ll need to include the prototype framework. The second bit of trickery is using the rel attribute to store the timestamp for each item. I prefer seconds since the Unix Epoch, but you can use whatever format you like as long as you can get the current time in the same format in javascript. At this point it’s a simple comparison, then changing the class if the items time is newer then the last visit time.

The HTML code for the items looks like this:


Item #1

Again all credit for this should go to OriginalSignal, unless they got this from somewhere else as well.

Popularity: 4% [?]