I am trying to scroll a div so that a link inside of it appears on top.
$(document).ready(function(){
scrollit();
});
function scrollit(){
var elem= $("#link10");
if(elem.length){
console.log(elem.offset().top);
$("#sidebar").animate({ scrollTop: elem.offset().top }, { duration: 'medium', easing: 'swing' });
}
}
#sidebar{
height:80px;
width:200px;
overflow:scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='sidebar'>
<a href='#' id='link1'>1</a><br/>
<a href='#' id='link2'>2</a><br/>
<a href='#' id='link3'>3</a><br/>
<a href='#' id='link4'>4</a><br/>
<a href='#' id='link5'>5</a><br/>
<a href='#' id='link6'>6</a><br/>
<a href='#' id='link7'>7</a><br/>
<a href='#' id='link8'>8</a><br/>
<a href='#' id='link9'>9</a><br/>
<a href='#' id='link10'>10</a><br/>
<a href='#' id='link11'>11</a><br/>
<a href='#' id='link12'>12</a><br/>
<a href='#' id='link13'>13</a><br/>
<a href='#' id='link14'>14</a><br/>
<a href='#' id='link15'>15</a><br/>
<a href='#' id='link16'>16</a><br/>
<a href='#' id='link17'>17</a><br/>
<a href='#' id='link18'>18</a>
</div>
<br/><br/>
<a href='#' onclick='scrollit();return false'>again</a>
Your code works fine as you can see in this jsbin
The problem is that the elem.offset().top
value is relative to the current scroll position so you have to take that in account and either reset the scroll or discount the scroll position (with something like window.pageYOffset
).
UPDATE:
Solution by danielb:
$("#sidebar").animate({ scrollTop: $("#sidebar").scrollTop()+elem.offset().top }, { duration: 'medium', easing: 'swing' });
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments