Animated scroll to anchor/id function with jQuery

Using the name attribute of the anchor tag has become obsolete so we have to find a new way to scroll to a certain point on the page when a link is being clicked. We want to do this animated, not just an instant jump to the target position.

animated scroll to anchor id script

The jQuery script we’re using for this works similar to our scroll back to top widget and it should be part of all your project and it’s as simple as possible.

The HTML code

<a href="#anchor1" class="scrollLink">Scroll to anchor 1</a>
<a href="#anchor2" class="scrollLink">Scroll to anchor 2</a>
<p id="anchor1"><strong>Anchor 1</strong> - Lorem ipsum dolor sit amet, nonumes voluptatum mel ea.</p>
<p id="anchor2"><strong>Anchor 2</strong> - Ex ignota epicurei quo, his ex doctus delenit fabellas.</p>

I added two links and two tags with the matching identifiers. I marked the scrolling links with a class: scrollLink and set its href attribute to match with the ID of the destination.

The script to use

$(document).ready(function(){
    $( "a.scrollLink" ).click(function( event ) {
        event.preventDefault();
        $("html, body").animate({ scrollTop: $($(this).attr("href")).offset().top }, 500);
    });
});

The script is placed inside the document.ready section so don’t forget to include jQuery when using this method.

I set an event listener to the scrollLink anchor tags and requested them not to behave like the default. The next line scrolls the HTML and Body elements to the requested position. You can speed up or slow down the scrolling speed adjusting the value at the end. The current 500 milliseconds means a half second.

Test the script in action on JSFiddle. For some reason the scrolling is not smooth but this is going to work when you do it on a live site.