1

I have a <ul> element. It's CSS overflow property is scroll.
I have several list elements in the list, such that there is a scrollbar.

<ul style="overflow: scroll; height: 100px;">
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   <li></li>
   ...
   <li></li> // how can I judge if this element is in the viewport?
</ul>

How can I determine if a specific list item is visible in that list?

Also, if it's not currently visible, what property can I use to make it scroll into view?

PS: No libraries, please (jQuery, MooTools, etc).

Joe Simmons
  • 1,768
  • 2
  • 10
  • 9
hh54188
  • 13,085
  • 30
  • 99
  • 174

2 Answers2

0

This is a function I just came up with.

I did some testing on the jsFiddle link at the end of this answer, and it seems consistent.


function elementInViewOfParent(elem) {
    var container = elem.parentNode;
    return (container.scrollTop + container.offsetHeight) >= elem.offsetTop &&
           (container.scrollTop - elem.offsetHeight) <= elem.offsetTop;
}



jsFiddle example - Just scroll it wherever you want, and click the button.
It checks for the red LI's visiblity, in this example.

Joe Simmons
  • 1,768
  • 2
  • 10
  • 9
-1

If you are okay with using jQuery, this will scroll so that elem is visible and at the top.

function scrollTo(elem) {
    var offset = $(elem).offset();
    $(window).scrollTop(offset.top);
}

(You could even animate the scroll: jQuery scroll to element).

Another solution would be to use <a target="foo"></a>, and the change the URL fragment to scroll to a particular element, but you specifically asked to be able to tell from JavaScript, which this does not allow you to do.

Community
  • 1
  • 1
Paul Draper
  • 64,883
  • 37
  • 172
  • 246
  • Well, jQeury's `offset` is nontrivial, but I believe you will have to rewrite it (or carefully copy and paste) to get what you want. – Paul Draper Nov 03 '13 at 09:24