Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anchor jump animation problems

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

like image 788
YSbakker Avatar asked Mar 12 '26 21:03

YSbakker


1 Answers

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/

like image 53
lozy219 Avatar answered Mar 14 '26 11:03

lozy219



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!