views:

226

answers:

1

I have the following markup:

<div style="overflow:auto;width:500px;height:100px;">
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
</div>

Mow I'm adding a new listitem with jQuery. How can I make it visible (scrolling the div to it) in case it's hidden?

I've tried UL.scrollTop(nuLI.top); but it didn't work.

+1  A: 

You need to call scrollTop() on the element with the overflow, which is the <div> element, not the <ul> element. Further you need to grab the top by element.position().top and you need to ensure that the <div> element is positioned relatively using position: relative, since the top is relative to the firstnext relative parent element.

Here's an SSCCE:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2621792</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"&gt;&lt;/script&gt;
        <script>
            $(document).ready(function() {
                $('#div').scrollTop($('#li3').position().top);
            });
        </script>
        <style>
            #div {
                position: relative;
                overflow: auto;
                width: 100px;
                height: 50px;
            }
        </style>
    </head>
    <body>
        <div id="div">
            <ul>
                <li>Item 1</li>
                <li>Item 2</li>
                <li id="li3">Item 3</li>
                <li>Item 4</li>
                <li>Item 5</li>
            </ul>
        </div>
    </body>
</html>
BalusC