A scrollable div whose elements can be seen

We have a scrollable div with CSS hieght:40px;. Inside it are several LIheight:20px

    <div id="#scroller">
<li title="I1">item1</li>
<li title="I2">item2</li>
<li title="I3">item3</li>
<li title="I4">item4</li>
<li title="I5">item5</li>
<li title="I6">item6</li>
<li title="I7">item7</li>
<li title="I8">item8</li>
<li title="I9">item9</li>
    </div>

When the user scrolls, I want to call a script that defines the first of two visible elements. Scrolling div is designed to bind to elements. Therefore, if you scroll down, and item3 and item 4 will be visible, how can I finance that element 3 is an element visible from above.

I tried $('#scroller li:visible'), but this does not work as far as the div is concerned, they are all visible only hidden behind the container.

Any ideas

Wonderful

+5
source share
4 answers
+10

, - scrollTop div li (, , , ).

0

jQuery position , , $("li").position().top;

So, I decided to write a loop to go through all the elements and find the one that has the least value for position().topand select it. Here's the script I wrote:

$(function() {

    var mostVisibleItem = $("li:first");

    var smallestOffset = mostVisibleItem.position().top;
    $("li").each(function(i, item) {
        if($(item).position().top < smallestOffset)
        {
            smallestOffset = $(item).position().top;
            mostVisibleItem = $(item);
        }
    });
    mostVisibleItem.css("color", "red");
});

You can see how this works in JSFiddle here: http://jsfiddle.net/P69y2/

Hope this helps :)

0
source

Something like this will work, where you replace console.log with your display logic.

<script>
    $(function() {
        $('#scroller').scroll(function() {
            $('#scroller li').each(function() {
                if ($(this).position().top > 0) {
                    console.log($(this).html());
                    return false;  // break once the first displayable value has been returned.
                }   
            })
        })
    })
</script>
0
source

All Articles