Scrollmarks: Using your browsers local storage

To try out the local storage API built into browsers, I wrote a small module that automatically saves your last scroll location on a page.

For example, say you’re reading a long blog post and you have to leave for some reason. You close your browser and and your pages are gone. Next time you load that page, a little javascript runs to check for a scroll location in your local browser storage. If it finds a value, it will use window.scrollTo and put you back where you left off.

It’s pretty simple, have a look at the code:

// @see http://drupal.org/node/756722
(function ($) {
// Due to a bug in older version of Firefox, need to add try/catch
$(document).ready(function(){
  try {
    // Check for local storage
    if (window['localStorage'] !== null) {
      // Get the last scrolled position
      if (localStorage.getItem('{scrollmark}' + window.location.href) !== null) {
        window.scrollTo(0, localStorage.getItem('{scrollmark}' + window.location.href));
        // @todo notify the user about the scroll
      }
      // Register the scroll even to track the last scrolled position
      $(window).scroll(function(e){
        localStorage.setItem('{scrollmark}' + window.location.href, $(window).scrollTop());
        // @todo find a more efficient way of marking the scroll location. Only set once scroll "stops"
      });
      // @todo add the capacity for manual setting of the scrollmark
      // @todo add scrollmark as query string parameter
    }
  }
  catch(e) {
  }
});
}(jQuery));

As you can see, I’ve got plans to allow the user to have better controls over the scrollmark and notify them when the scroll is about to be set (and maybe an override).

But it’s a great example on how to use local storage. For more information, have a look here http://diveintohtml5.org/storage.html