check if element got scrolled to top

Top Questions picture Top Questions · Sep 23, 2013 · Viewed 38k times · Source

I want to check if an element is scrolled to top with an offset of ~ 100px.

I´ve got a page with 5 subcontents and 2 classes to make backgrounds. It looks like this:

<div class="background1">
Content1
</div>
<div class="background2">
Content2
</div>
<div class="background1">
Content3
</div>
<div class="background2">
Content4
</div>
<div class="background1">
Content5
</div>

Now i want to check, when one of these classes reaches the top by scrolling

This is one of my last trys:

$('.background1', '.background2').position(function(){
             if($(this).position().top == 100){
            alert('checkThis');
        }
        }); 

I think this is my closest try by now...of course this code is in document.ready and at the end of my code....

TLDR: How to check if an element got scrolled to top (and some offset)?

Answer

adeneo picture adeneo · Sep 23, 2013

You have to listen for the scroll event, then check each element against the currently scrolled distance, something like :

$(window).on('scroll', function() {
    var scrollTop = $(this).scrollTop();

    $('.background1, .background2').each(function() {
        var topDistance = $(this).offset().top;

        if ( (topDistance+100) < scrollTop ) {
            alert( $(this).text() + ' was scrolled to the top' );
        }
    });
});