Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 421
Mark Milford Avatar asked Feb 09 '10 16:02

Mark Milford


People also ask

How to check if element is visible after scrolling jQuery?

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.

How do you know if an element is visible in the screen during scrolling?

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.

How can I tell if a div is in a viewport?

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.


2 Answers

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.

like image 169
kevingessner Avatar answered Nov 09 '22 10:11

kevingessner


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()

like image 4
Stanislav Avatar answered Nov 09 '22 09:11

Stanislav