Search code examples
jqueryscrollanchorparallaxsmoothing

Scrolling to anchor in a div jquery


I got some problems with a smooth scroll to anchors in a parallax div with a fixed nav.

The script works fine from the top of the page but once in the content, links drive to bad anchors...

I tried several scripts but encounter the same problem (works fine from top but fails from content).

$(document).ready(function() {
$(".scroll").click(function (e) {
    e.preventDefault();
    if (this.hash) {
        //get rid of hash
        var hash = this.hash.substr(1);

        //get the position of the <a name> 
        var $toElement = $("[id=" + hash + "]");
        var toPosition = $toElement.offset().top;

        //scroll/animate that element
        $(".parallax").animate({
            scrollTop: toPosition
        }, 500);
    }
});

});

Here is the code: http://jsfiddle.net/63hy5urr/1/

kindly please help.

Thank you.


Solution

  • You must check where .parallax is currently scrolled at by using the scrollTop() method and then add this value to toPosition when animating:

    $(".parallax").animate({
        scrollTop: $(".parallax").scrollTop() + toPosition
    }, 500);
    

    Working fiddle: http://jsfiddle.net/63hy5urr/3/