Danielle Powell Danielle Powell - 5 months ago 11
jQuery Question

jQuery srollTop conundrum

I am currently having difficulty with the scrollTop() function in jQuery. At the moment, the smooth scrolling feature is scrolling past the intended section, then bouncing back to it once the function has completed running. I have included a jsFiddle at the end of this, but here is my script at the moment:

html:

<nav id='menu2' class='menu2'>
<ul>
<li class='marker'></li>
<li class='item2'><a id='step1link' href='#bs1'>Baby Step 1</a></li>
<li class='item2'><a id='step2link' href='#bs2'>Baby Step 2</a></li>
<li class='item2'><a id='step3link' href='#bs3'>Baby Step 3</a></li>
</ul>
</nav>

<div class='content'>
<section class='babystep' id='bs1'>
<h1>Baby Step 1</h1>
<h5>second-title</h5>
<p>content</p>
<p>content</p>
</section>

<section class='babystep' id='bs2'>
<h1>Baby Step 2</h1>
<h5>Pay off all debt using the Debt Snowball</h5>
<p>content</p>
<p>content</p>
</section>

<section class='babystep' id='bs3'>
<h1>Baby Step 3</h1>
<h5>second-title</h5>
<p>content</p>
<p>content</p>
</section>


Javascript:

$(document).ready(function() {
$('a').on('click', function(e) {
if(this.hash !== "") {
e.preventDefault();

const hash = this.hash;

$('.content').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
window.location.hash = hash;
})
}
})
})


I have tried the suggested $('html,body') instead of $('.content'), which only succeeded in scrolling the entire page, not the div with section elements that need to be scrolled.

jsFiddle: https://jsfiddle.net/hollisd09/wa67wLc1/

Rio Rio
Answer

Change this line:

scrollTop: $(hash).offset().top

into this:

scrollTop: $(hash).offset().top - $('.content').offset().top + $('.content').scrollTop()