I have a navigation on my website that is powered by jQuery to smooth-scroll to the target ID, but it is acting very strange (Chrome, Firefox):
- Sometimes it doesn't actually move to the target ID all the way
- If you click a second time on the target it scrolls you back up to the header
Here is a gif demonstrating this weird behavior on my website.
I made a simplistic version of my website so you can test it yourself, where you can experience the same weird behavior.
I made it as identical as possible. The HTML, classes, ID's and jQuery are exactly the same. I also gave the navigation a fixed
position, just like the one on my website.
The jQuery code in question:
$("#scrollOne").click(function() {
$('html,body').animate({
scrollTop: $("#one").offset().top
}, 750);
});
In short, what could the problem be with code that would cause this strange behavior? Am I using the wrong method for jQuery and if so, is there a better one? I don't mind using a library, but I'd prefer not to.
The problem is that you have
height:100%
on thebody
, so the offset returns wrong values (correct, but not what you expect).Give
height:auto
andmin-height:100%
tobody
and it will work correctly.See updated pen: https://codepen.io/anon/pen/qJPPeL?editors=1010
Here's a working version. Apparently this is due to the
overflow-x:hidden
frombody
's CSS rule. See this question.Removed that rule, now it seems perfectly fine (or prefer the codepen below that, since SO's fullpage version is bugging out a bit):
Codepen version
Unrelated: I would also suggest adding
.stop()
before each.animate()
call so every new animation stops the previous one.offset().top
values change when page scrolled. so, you need to save those values at the beginning, also you should re-assign those values when window size changes.code: https://codepen.io/peker-ercan/pen/wYrrWV?editors=1010