How to dynamically check if items fall at the top of a window

I have several elements under each other. I want to check when these elements get to the top of the window. I know how to do this with a single element, but not with multiple elements.

Single item:

$(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 the class 'test'. And if the .test element reaches the top, I want to say: div 1 reached the top; div 2 reached the top; etc. So he should see which div it is (maybe get the attr id or something else?)

This is what I have 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!

+4
source share
2 answers

I’m a little vague from what you mean by reaching the top, by which I mean that it scrolls out of sight or it is visible or it’s definitely above. However, I think the math is simple after the answer, and what you really need to do is check every div.test inside the scroll function. You can get an identifier or even inner text or whatever you need to register it.

This will tell you which ones are the visible period, if you want to fully see that this is a different calculation. You should keep in mind that the scroll event fires more often than you think.

 $('#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')); } }); }); 

the violin is here

+2
source

Just check if the scroll is larger than the top position of the elements (y position).

 $(window).scroll(function(){ if ($(window).scrollTop() > $('#element').position().top) { console.log('#element hits top!'); } }); 
+1
source

All Articles