13

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>
</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?

Thanks

Mark

Mark Milford
  • 1,180
  • 1
  • 15
  • 32

3 Answers3

17

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) {
            $(this).addClass('top');
            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.

Community
  • 1
  • 1
kevingessner
  • 18,559
  • 5
  • 43
  • 63
  • Thanks, works great with a minor tweak, adding a number of the 25 so that they get selected just before they hit the top of the window, otherwise the selected one is half scrolled away before the next one is selected – Mark Milford Feb 10 '10 at 09:48
  • $('.item').offset() won't work as - offset will get the current coordinates of the first element in the set of matched elements, relative to the document. – paraS elixiR Oct 03 '17 at 13:18
5

Here is one more idea, based on built-in javascipt functions.

var range = document.caretRangeFromPoint(0,0); // screen coordinates of upper-left corner of a scolled area (in this case screen itself)
var element = range.startContainer.parentNode; // this an upper onscreen element

This bit of code is not a ready-to-use product — it's just an example, that works only in webkit browsers. If you want to use it, you should google for cross-browser equivalents of caretRangeFromPoint()

Stanislav
  • 410
  • 3
  • 11
-6

You can create your own scroller using javascript.

It's not very practical idea but you can try.

And place the link to the image describing it better. It would be very usable.

oneat
  • 10,778
  • 16
  • 52
  • 70
  • Adding an implementation sample, or at least an implementation paradigm or technology, would be useful. Describe better, e.g.: what do you mean with scroller, what library/plugin would you use, why wouldn't you consider it a practical idea, etc. – Luis Masuelli Mar 27 '14 at 17:07