JavaScript: isScrolledIntoView


I needed a simple way to detect when a placeholder DIV (that would contain an image) had scrolled into the current viewport of the browser. I’ve seen a few solutions that worked, and a few that didn’t (hello? test your code!). Here’s my simple solution:

function isScrolledIntoView(elem) {
    elem = $(elem);
    var win = $(window);
    var docViewTop = win.scrollTop();
    var docViewBottom = docViewTop + win.height();
    var elemTop = elem.offset().top;
    var elemBottom = elemTop + elem.height();

    var a = (elemTop > docViewBottom);
    if (a) { return false; }
    var b = (elemBottom > docViewTop);
    if (!b) { return false; }
    return !(a && b);

Nothing fancy, except it does require jQuery.

When one of the place holder DIVs scrolled into view, the code would trigger a queued load of the image.


As the SmugMug API is poorly designed in a few places, in particular as it relates to showing a thumbnail for a gallery/album, when an album/gallery is scrolled into view, the app loads a list of ALL of the images from the now visible album and selects one of them to show as the thumbnail. It’s extremely inefficient unfortunately. Instead, if they could have included that extra piece of data in the gallery list (thumbnail image and thumbnail image key), boom!

I’ve also included a delay so that the auto loading only occurs after a 1 second pause (either the window being resized or scrolling occurring):

function delayLoadNewVisible() {
    if (visibilityDelayTimerId == 0) {
        visibilityDelayTimerId = window.setTimeout(function () {
            visibilityDelayTimerId = 0;
        }, 1000);

I’m not going to post the code for the other useful aspect of this functionality, but I’ll tell you about it, and leave coding it as an exercise for the reader. Smile

When the user scrolls new albums into view, after the pause, they’re added to a load queue. However, as it’s just as likely that the user will scroll the album off the screen, my load code also can remove something from the load queue if it hasn’t been loaded already. This way, visible albums are given precedence. By using the queue in this way, there are a manageable number of outstanding requests at any given time, and ideally only those that are relevant to what’s on the user’s screen.