星期一, 9月 03, 2012

[jQuery API] 實作Facebook的捲軸拉到底更新資訊 Facebook like scroll bar detection

如何使用jQuery偵測捲軸的位置!! 實作Facebook like的更新狀態列記錄
$(function () {
             var $win = $(window);

             $win.scroll(function () {
                 if ($win.scrollTop() == 0)
                     alert('Scrolled to Page Top');
                 else if ($win.height() + $win.scrollTop()
                                == $(document).height()) {
                     alert('Scrolled to Page Bottom');
                 }
             });
         });


Here's some explanation:

$(window).height() - returns height of browser viewport

$(document).height() - returns height of HTML document

$(window).scrollTop() – returns the current vertical position of the scroll bar.

So if the scroll bar is at the very top, the value of $(window).scrollTop() will be Zero. Similarly if the value of the browser viewport + vertical position of scroll bar = document height, then the user has scrolled to the bottom of the page.

寫成外掛的方式來看看!!



(function($) {
 
 $.scrollHandler = function(options){
  
  var _defaultSettings = {
    top :function(){
     $.console('[scrollHandler] Scrolled to Page Top');
    },
    bottom :function(){
     $.console('[scrollHandler] Scrolled to Page Bottom');
    }
  };
  
  var opts = $.extend(_defaultSettings,options);
  
  var $win = $(window);
        $win.scroll(function () {
          var currentPos = $win.scrollTop();
          //$.console("current pos:" + currentPos);
             if (currentPos == 0)
              opts.top();
             else if ($win.height() + currentPos == $(document).height()) {
              opts.bottom();
             }
        });
 };
 
})(jQuery);
Reference:
facebook like scroll detection in Javascript (jquery) to get more records of server
Use jQuery to Detect if User has Scrolled to the Bottom or Top of a Page

沒有留言:

張貼留言

留個話吧:)