So another question regarding my website: I'm trying to animate the "anchor jump" using JQuery and I'm using the following code. As it seems to me, this should work, but it doesn't quite.
Forgot to mention: Whenever any of the buttons in the header is pressed, the anchor jump should be performed.
$(function () {
$("a").click(function () {
if (this.hash) {
var hash = this.hash.substr(1);
var $scrollToElement = $("a[name=" + hash + "]");
var scrollToPosition = $scrollToElement.position().top;
$("html, body").animate({
scrollTop: scrollToPosition
}, 1000, "swing");
return false;
}
});
});
<div name="home" id="body_container">
<div id="banner_container">
<img id="banner" />
</div>
<div id="content_container">
<div name="over" id="over_content"></div>
<div name="contact" id="contact_content"></div>
</div>
</div>
You can see all the code in the JSFiddle
In addition to Harry's solution, you should change
var scrollToPosition = $scrollToElement.position().top;
to
var scrollToPosition = $scrollToElement.offset().top;
position() gives you the relative offset to the container (which is 0 in your case), and offset will give you the offset to you whole document, and that helps you scroll correctly.
try this http://jsfiddle.net/eax7ppwb/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With