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
getBoundingClientRect() if (top <= rect. bottom === false) return false // Check if the element is out of view due to a container scrolling if ((top + height) <= rect. top) return false el = el.
To know whether the element is fully visible in viewport, you will need to check whether top >= 0, and bottom is less than the screen height. In a similar way you can also check for partial visibility, top is less than screen height and bottom >= 0.
If the <div> element is in the viewport, its top and left are always greater than or equal zero. In addition, its distance from the right is less than or equal to the width of the viewport, and ids distance from the bottom is less than or equal to the height of the viewport.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With