3

I have a scrolling div containing list items. I have this boilerplate scroll event defined

$("#scrollingDiv").scroll(function(e) {

});

Inside of this scroll event function, how can I figure out which elements are at the top and bottom of the currently visible area?

Peter Olson
  • 139,199
  • 49
  • 202
  • 242
  • 1
    Maybe you can iterate through the listed items checking if they are visible and create an array. then take the first and last ones. Check this out http://stackoverflow.com/questions/487073/jquery-check-if-element-is-visible-after-scroling, You can use that as a function if you wanted, then iterate through your list and check each element. – Matt Aug 18 '11 at 05:32

1 Answers1

3

You could try computing the positions of the list items with respect to the scrolling <div> and then scan the positions to see which ones match up with the scrollTop of the <div>.

Something like this perhaps:

var base = $('#scrollingDiv').offset().top;
var offs = [ ];
$('li').each(function() {
    var $this = $(this);
    offs.push({
        offset: $this.offset().top - base,
        height: $this.height()
    });
});
$("#scrollingDiv").scroll(function() {
    var y = this.scrollTop;
    for(var i = 0; i < offs.length; ++i) {
        if(y < offs[i].offset
        || y > offs[i].offset + offs[i].height)
            continue;
        // Entry i is at the top so do things to it.
        return;
    }
});

Live version (open your console please): http://jsfiddle.net/ambiguous/yHH7C/

You'd probably want to play with the fuzziness of the if to get something that works sensibly (1px visible hardly makes an element the top one) but the basic idea should be clear enough. Mixing in the height of #scrollingDiv will let you see which <li> is at the bottom.

If you have a lot of list items, then a linear search might not be what you want but you should be able to solve that without too much effort.

mu is too short
  • 426,620
  • 70
  • 833
  • 800