How to scroll smoothly with jQuery

[box type="alert" size="large"] Please notice: there's an updated version of this snippet.

Check out the new version Smooth Scroll Effect to anchor - jQuery.

[/box]

We will add a jQuery function to create smooth scroll in our anchor links.

jQuery Animate

You can customize the speed of the effect.

Change the 2000 for 1000 (faster) or 5000 (slower).

$(function(){

$('a[href*=#]').click(function() {

if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {

var $target = $(this.hash);

$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');

if ($target.length) {

var targetOffset = $target.offset().top;

$('html,body').animate({scrollTop: targetOffset}, 2000);

return false;

}

}

});
});

Download Demo

Full Code





Example 17 | CodeGround


Go back and leave a Comment


About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.
3 comments

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*