neilgee
neilgee

Reputation: 538

How can I animate the scrollTop function with animate

I am using a function to store a position where i want the page to reload to when clicked, function works fine but I would like to animate the scroll.

;(function($){

/**
 * Store scroll position for and set it after reload
 *
 * @return {boolean} [loacalStorage is available]
 */
$.fn.scrollPosReload = function(){
    if (localStorage) {
        var posReader = localStorage["posStorage"];
        if (posReader) {
            $(window).scrollTop(posReader);
            localStorage.removeItem("posStorage");
        }
        $(this).click(function(e) {
            localStorage["posStorage"] = $(window).scrollTop();
        });

        return true;
    }

    return false;
}

/* ================================================== */

$(document).ready(function() {
    // Trigger the reload
    $('#edit').scrollPosReload();
});

}(jQuery));  

Any ideas...

Upvotes: 1

Views: 274

Answers (1)

Rafael
Rafael

Reputation: 18522

You can animate() a scrollTop property. The only problem is that window object doesn't have a scrollTop property, only element nodes have it. The jQuery scrollTop() method has extra implementation to work on window and document.

So, in order to scroll the page in animated manner, usually this code is used

$('html, body').animate({scrollTop: posReader});

(The selector contains both html and body elements due to some browser inconsistencies (didn't check if the issue still exists)).

Also, the localStorage stores and retrieves data as strings, so it's a good idea to cast the read value to number, although often it won't make a difference for jQuery.

Full code:

;(function($) {

  /**
   * Store scroll position for and set it after reload
   *
   * @return {boolean} [loacalStorage is available]
   */
  $.fn.scrollPosReload = function() {
    if (window.localStorage) {
      var posReader = localStorage["posStorage"];

      if (posReader) {
        $('html, body').animate({
          scrollTop: +posReader
        });
        localStorage.removeItem("posStorage");
      }

      $(this).click(function(e) {
        localStorage["posStorage"] = $(window).scrollTop();
      });

      return true;
    }

    return false;
  }

  /* ================================================== */

  $(document).ready(function() {
    // Trigger the reload
    $('#edit').scrollPosReload();
  });

}(jQuery));

JSFiddle example

Upvotes: 1

Related Questions