Check the comments in code for explanations. This example relies on jQuery.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function scroll_item() { var tracked_item = $(".list_item").last(); // grabs the last "item" with the class list_item // $(window).outerHeight() is the height of the browser window // tracked_item.offset().top is the vertical amount of pixels from(below) the top of the web page document var scrollPosition = tracked_item.offset().top - $(window).outerHeight(); // figures out how many pixels below the // initial browser window is the tracked item. So if the window is 700px vertically and the item that is being tracked // is 1200px from the very top of the document.. then the user needs to scroll 500 more pixels to reach the // tracked item. $(window).scroll(function(event) { // applies an event listener to the document window // $(window).scrollTop() is how many pixels that are hidden(above) the element ( window in this case ) if (scrollPosition > $(window).scrollTop()) { // checks if there are more pixels left to scroll(scrollPosition) // then what has been scrolled already($(window).scrollTop()) return; // since the amount left is greater then what has been scrolled... do nothing, tracked_item isn't visible yet. } // finally the amount of pixels scrolled ($(window).scrollTop()) is larger then the amount needed to scroll // to the tracked_item. $(this).off(event); // temporarily remove this scroll event from the window. add_to_items(); // lazy load and append new item. If desired, at the end of the add_to_items make // sure to re-call scroll_item() to reattached the event listener to the window. }); } |