How to scroll smoothly with jQuery

Please notice: there's an updated version of this snippet.

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


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; } } }); });

Demo

View Demo

Full Code

<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Example 17 | CodeGround</title> </head> <body style="background:url(http://cdn.quicoto.com/codeground/bg.jpg) repeat-x top left;"> <div style="height:1000px; padding:30px;"><a href="#CodeGround">Click me to scroll down!</a></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script> $(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; } } }); }); </script> <a name="CodeGround"></a> <p style="margin:30px 0px 50px 30px;"><a href="https://ricard.dev/how-to-scroll-smoothly-with-jquery">Go back and leave a Comment</a></p> </body> </html>
3 comments
  • Itยดs broken in Google chrome v12

    • Ouch, that’s right Marcus. Even updating the jQuery ๐Ÿ™

      It worked before, I’ll try to find a solution.

      EDIT: Works on Firefox 5 and IE8.

      Thanks for reporting ๐Ÿ˜‰

  • Yes it was working perfect and now it is not working.
    It is the simplest code you can find online. Any idea of a fix? Thanks

Leave a Reply

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

*
*