I have a scrollable ul, and several li-items. My goal is to scroll to the li-item with certain id when the user presses a button.
I have a code which seems to work, but there are two issues
I guess, both issues are because of some relative coordinates, but I can't figure out how this system works. Help me please!
HTML:
<ul id="container">
<li id="1">stuff1</li>
<li id="2">stuff2</li>
<li id="3">stuff3</li>
<li id="4">stuff4</li>
<li id="5">stuff5</li>
<li id="6">stuff6</li>
<li id="7">stuff7</li>
<li id="8">stuff8</li>
<li id="9">stuff9</li>
<li id="10">stuff10</li>
<li id="11">stuff11</li>
<li id="12">stuff12</li>
<li id="13">stuff13</li>
<li id="14">stuff14</li>
<li id="15">stuff15</li>
<li id="16">stuff16</li>
</ul>
<button id = 'btn'>Scroll to element with id = 9</button>
JS:
var $container = $('#container')[0];
// $container.scrollTop = $container.scrollHeight;
// If I uncomment the above line, the code does not work any more
$('#btn').click(function(){
$container.scrollTop = $('#9').position().top;
});
CSS:
ul {
overflow-y: auto;
position: relative;
height: 300px;
width: 300px;
background: red;
}
ul li {
margin: 30px;
border: solid;
}
See the JSFiddle
The 9 element will be positioned relative to the scroll too. You have to append the current scroll to the 9 position, like this: http://jsfiddle.net/rck1ow93/2/
$container.scrollTop = $container.scrollTop+$('#9').position().top;
To add to Jorge's answer, in addition to taking scroll into account, you might want to use .offset() instead of .position(), as it will give you the correct position. So change
$container.scrollTop = $('#9').position().top;
to
$container.scrollTop += $('#9').offset().top;