Question

I'm writing a infinity scroll function for my app that will preload pages once the user scrolls up or down. The (Cordova/Phonegap) app will display pages that are dynamically created like this:

<!-- Contents -->
<div id="page-container">
<div id="scroller">
    <div id="page_1" class="pagina"></div>
    <div id="page_2" class="pagina"></div>
    <div id="page_3" class="pagina"></div>
    <div id="page_4" class="pagina"></div>
    <div id="page_5" class="pagina"></div>
    <div id="page_6" class="pagina"></div>
</div>

I want to know which of these page_blabla id's is currently in the viewport so I can determine the next and previous pages to preload. How would one achieve this? The result needs to be a function that returns the id of the page currently in the viewport.

I've seen several examples where people determine if a specific element is in the viewport, but that's not what I need. I want to return the id of the page(div) that is currently in the viewport.

Thx in advance!

Was it helpful?

Solution 2

It's just a small leap from the examples you linked to, let's assume you have isElementInViewport from your example link, test each page's <div> for being in the viewport until you get a match, then return that Node's id .

var pages = document.getElementsByClassName('pagina');
function getCurrentPageId() {
    var i;
    for (i = 0; i < pages.length; ++i)
        if (isElementInViewport(pages[i]))
            return pages[i].getAttribute('id');
}

OTHER TIPS

JQUERY SOLUTION:

After you need just call function isOnScreen for a detection.

$.fn.isOnScreen = function(){

    var win = $(window);

    var viewport = {
        top : win.scrollTop(),
        left : win.scrollLeft()
    };
    viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();

    var bounds = this.offset();
    bounds.right = bounds.left + this.outerWidth();
    bounds.bottom = bounds.top + this.outerHeight();

    return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

};

Based on this DEMO:
http://jsfiddle.net/moagrius/wN7ah/

Original is edited from this article:
http://upshots.org/javascript/jquery-test-if-element-is-in-viewport-visible-on-screen

And maybe this can help :) as well
http://www.teamdf.com/web/jquery-element-onscreen-visibility/194/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top