How can I execute a function on an element as soon as it comes into view of the window when I scroll down?
            Asked
            
        
        
            Active
            
        
            Viewed 979 times
        
    1
            
            
        - 
                    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 Answers
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
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
 
     
    