views:

31

answers:

1

Some sites have tables which appends rows when you scroll the browser so that the bottom of the table is visible.

Guess it's something like this:

  1. jQuery detects that the end of the table is visible in the browser
  2. $.getJSON is used to fetch the next rows from the server
  3. the rows are appended.

Questions:

  1. How do I detect that the last row is visible in the browser?
  2. Is there a better way than $('#tableId tbody tr').length to get the current number of rows?
A: 

(1) Detect whether the last row is visible:

$(window).scroll(function(){
    var $window = $(this),
        $el = $('#tableId tbody tr:last'),

        viewPaneTop = $window.scrollTop(),
        viewPaneBottom = viewPaneTop + $window.height(),

        elementTop = $el.offset().top,
        elementBottom = elementTop + $el.height();

    if ((elementTop >= viewPaneTop) && (elementBottom <= viewPaneBottom)) {
        // add new rows here
    }
});

(2) That's the correct way to determine the number of rows.

lonesomeday