Search code examples
jqueryanchoreasing

Javascript anchor scrolling at even speed


I have this section of code which does smooth scrolling to anchor points within my code (technically not my code, I'm modding a template), but my problem is that it goes at 1400ms regardless of where down the page it is, so the ones at the top go pretty slow, but some that are further down, it drops like a stone. Is it possible to read how far down the ID tag is and alter the duration, so that I can kind of generalise the speed?

$(".menu a").click(function () {
    $("html, body").animate({
        scrollTop: $($(this).attr("href")).offset().top + "px"
    }, {
        duration: 1400,
        easing: "swing"
    });
    return false;
});

Solution

  • You already retreive the offset on the top with this code $($(this).attr("href")).offset().top.

    So all you need to do is calculate the speed, like:

    duration:  $($(this).attr("href")).offset().top / 2 // = 500px per second.