Ben Shelock
Ben Shelock

Reputation: 20993

When element comes into view of the window execute function

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

Upvotes: 1

Views: 1057

Answers (2)

Per H
Per H

Reputation: 1542

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.

Upvotes: 1

easement
easement

Reputation: 6139

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

Upvotes: 1

Related Questions