the Forum

Getting the ID of the visible DIV on scroll

Posted on April 25, 2013 by Michael Rosario
Total Posts: 33  |  Join date: 03-12-11

So I wanted a way to find out which DIV is currently visible to the user while scrolling. I have containers of news with the class "NewsItem." As the user scrolls, I want to know which news item he/she is looking at. To accomplish this I wrote the following scroll script. I'm sure there are better ways to optimize this.

var offset = 505; /* Average number of heights */
$(document).scroll(function(){
$(".NewsItem").each(function(){  
	var scroller = $(this).position().top*1-offset;
	if($(document).scrollTop() > scroller && $(document).scrollTop() <  $(this).position().top){
		current = $(this).attr("id");
	}
});
});

Tags: There are no tags for this entry.

There are no answers yet.  Add yours below.

add your answers here
comments powered by Disqus