We can scroll to an element which is inside a div which has scrollbar using jQuery.animate()
and for scrollTop
pass in $(elemId).parent().scrollTop() + $(elemId).offset().top - $(elemId).parent().offset().top
The scrollTop()
method sets or returns the vertical position of the scrollbar for the selected elements. The offset()
method allows us to retrieve the current position of an element relative to the document.
The idea is add the current offset of the scrollbar with the current offset of the element, and subtract the top offset of the parent element, i.e., the area which is fixed below which the scroll area beings. Offset on an element relative to the document can be positive or negative, depending on whether the element is yet to be scrolled or the element has passed the scrolling.
Sample code
<html>
<head></head>
<style>
.content {
height: 300px;
overflow-y: scroll;
}
</style>
<body>
<header></header>
<nav>
<!-- link to navigation to sections -->
</nav>
<article class="content">
<section>
<div></div>
<p></p>
</section>
<!-- more sections here -->
</article>
</body>
</html>
// js
$('.content').animate({
scrollTop: $(elemId).parent().scrollTop() + $(elemId).offset().top - $(elemId).parent().offset().top
}, {
duration: 1000,
specialEasing: {
width: 'linear',
height: 'easeOutBounce'
},
complete: function (e) {
console.log("animation completed");
}
});