Reputation: 7599
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.
Upvotes: 1
Views: 11341
Reputation: 99
I have tried @BalusC method, but the scroll will bounce back if it has already reached the bottom. Then I figured out, by inserting ".scrollTop(0)" before the actual scrollTop will maintain the scroll position.
$('#div').scrollTop(0).scrollTop($('#li3').position().top);
Upvotes: 0
Reputation: 1108722
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"></script>
<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>
Upvotes: 6