Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the full height of an UL with overflow set?

Tags:

jquery

I have a UL with an overflow-y:scroll; set so it scrolls. How to I get the full height of the list as $(ul).height() just gives the height of the scroll viewport not the height of the full list.

html

<ul style="overflow-y:scroll; height: 50px;">
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
    <li>item</li>
</ul>

Things like Get The Full Height Of HTML Element That's Partially Hidden By Overflow:Hidden With JQuery / Javascript wont work as there is no inner wrapper, there is just the list.

I'm trying to get the list to scroll to the bottom when I append a new item, but...

$("ul").attr({ scrollTop: NeedHeightHere });

like image 384
Justin808 Avatar asked Dec 12 '22 07:12

Justin808


1 Answers

Use the scrollHeight DOM property, supported by all modern browsers (even by IE):

var wholeHeight = $("ul")[0].scrollHeight;

Alternatively, you can select the first and last item in the list, get the top offset, and substract these from each other. Add the height of the final list element, and the result is equivalent to the scrollHeight (after adding top and bottom paddings of UL).

var ul = $("ul"),
    last = ul.children().last();
var wholeHeight = last.offset().top - ul.children().first().offset().top
                  + last.outerHeight()
                  + parseFloat(ul.css("padding-top"))
                  + parseFloat(ul.css("padding-bottom"));

Note: The first method is much more efficient. The second method might fail to produce the right result when the last element is absolutely positioned, or floating.

like image 183
Rob W Avatar answered Dec 29 '22 13:12

Rob W