Mark Milford Mark Milford - 8 months ago 53
jQuery Question

Jquery / Javascript find first visible element after scroll

I have code like below:

<div id="container">
<div class="item" id="1">blah blah</div>
<div class="item" id="2">blah blah 2</div>

But actually there are lots and lots of with class='item'.

Basically as the user scrolls this great long list of items I want to change the style of the current top visible one (like google reader!). Have looked around for solution in jquery or plain javascript but can't seem to find one. Anyone have any ideas?




If your elements aren't the same height, you can iterate over them on scroll:

$(document).scroll(function() {
    var cutoff = $(window).scrollTop();
    $('.item').removeClass('top').each(function() {
        if ($(this).offset().top > cutoff) {
            return false; // stops the iteration after the first one on screen

If this is too slow, you can cache the $('.item').offset() into an array, rather than calling offset() each time.