Jquery – How to dynamically check if elements hit top of window

eachjqueryscrolltop

I have multiple elements below each other. I want to check when these elements hit the top of the window. I know how to do it with a single element, but not with multiple elements.

Single element:

$(function(){   
var itemOffset = $('.test').offset().top;

$(window).scroll(function(){
    var scrollTop = $(window).scrollTop();
    if(scrollTop >= itemOffset){
        console.log("item has reached the top");
        }
});});

But now i have 5 elements with class 'test'. And if a .test element reaches the top, i want to say: div 1 has reached the top; div 2 has reached the top; etc. So it has to see which div it is (maybe fetch the attr ID or something?)

This is what I had so far.

$(function(){   
$('.test').each(function(){
    var itemOffset = $(this).offset().top;

    $(window).scroll(function(){
        var scrollTop = $(window).scrollTop();
        var toet = itemOffset - scrollTop;

        if(scrollTop >= itemOffset){console.log("New div has reached the top!")}
    });     
});});

Help is greatly appreciated!

Best Answer

I'm a little fuzzy on what you mean by reached the top, by which I mean did it scroll out of view or is it visible or is it exactly at the top. That said, I think the math is simple once that is answered and what you really need to do is check each div.test inside the scroll function. You can get the id or even the inner text or whatever when you need to log it.

This will tell you which ones are visible period, if you want completely visible that is a different calculation. One thing you have to keep in mind is that the scroll event fires more often than you think it does.

$('#container').scroll(function(){
    $('.test').each(function(){
        var itemOffset = Math.abs($(this).offset().top);
        var height = $('#container').height();
        if (itemOffset > 0 && itemOffset < height) {
             alert($(this).attr('id'));
        }
    });
});

fiddle over here