Created
February 20, 2019 21:15
-
-
Save rowej83/a268763b8e774c237ad24ba6afa797a9 to your computer and use it in GitHub Desktop.
How to check if item is scroll to on the screen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment