1

How can I execute a function on an element as soon as it comes into view of the window when I scroll down?

Ben Shelock
  • 20,154
  • 26
  • 92
  • 125
  • http://stackoverflow.com/questions/2138307/dynamically-changing-dom-elements-as-they-gets-scrolled-into-view-performance In that question I have code that'll do what you want. – Per H Mar 22 '10 at 20:59

2 Answers2

1
function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

via https://stackoverflow.com/questions/487073/jquery-check-if-element-is-visible-after-scroling

Community
  • 1
  • 1
easement
  • 6,119
  • 3
  • 29
  • 36
1

I might as well post it here as an answer:

function elementInView($elem, vps, vpe) {
    var elempos = $elem.position(); 
    var pagestart = elempos.top + vps;
    var pageend = elempos.top + vps + $elem.height();
    var offset = $elem.height() - Math.max(0,vps-pagestart) - Math.max(0,pageend-vpe);    
    return (vpe > 0 && offset > -200); 
}

$('#container').bind('scroll', function() {
    var $container = $(this);
    var vps = $container.scrollTop();
    var vpe = vps + $container.height();

    $('li', '#container').each(function() {
        var $this = $(this);
        if (elementInView($this,vps,vpe)) {
            // $this is now in view
        }
    });
});

I realize this has some performance issues, and can be optimized, but it should be a start.

Per H
  • 1,542
  • 10
  • 19