JulianJ
JulianJ

Reputation: 1313

Ease into scrolling to anchor links?

I am using this piece of jquery that finds any anchor links on the page and lets me scroll to them. It works really well but I'm trying to figure out how I can make the scrolling ease in and out of the scroll.

Thanks.

//Scroll to anchors
    $('a[href^="#"]').on('click', function(event) {
    var target = $(this.getAttribute('href'));
    if( target.length ) {
        event.preventDefault();
        $('html, body').stop().animate({
            scrollTop: target.offset().top -100
        }, 1000);
    }

    //end of scroll code
});

Upvotes: 0

Views: 320

Answers (1)

Dan Philip Bejoy
Dan Philip Bejoy

Reputation: 4391

jQuery animate() takes a timing function as an argument

The syntax is

.animate( properties [, duration ] [, easing ] [, complete ] )

So you can add

$('html, body').stop().animate({
        scrollTop: target.offset().top -100
    }, 1500, "swing");

By default it is swing which progresses slightly slower at the beginning and end of the animation than it does in the middle of the animation much like ease in and out. Then there is linear which progresses at a constant pace throughout the animation.

$('html, body').stop().animate({
        scrollTop: target.offset().top -100
    }, 1500, "linear");

You can also try increasing the duration to soften up the easing transition.

Upvotes: 1

Related Questions