Danielle Powell Danielle Powell - 1 year ago 52
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:


<nav id='menu2' class='menu2'>
<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>

<div class='content'>
<section class='babystep' id='bs1'>
<h1>Baby Step 1</h1>

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

<section class='babystep' id='bs3'>
<h1>Baby Step 3</h1>


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

const hash = this.hash;

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 Source

Change this line:

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

into this:

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