Animated scroll to anchor/id function with jQuery

The usage of the name characteristic of the anchor tag has grown to be out of date so we must discover a new way to scroll to a certain factor at the web page when a hyperlink is being clicked. We need to do that animatednot simply an instant leap to the goal function.

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: scrollLinkand set its href attribute to match with the ID of the destination.

The script code

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

We hope this code will work for you!

Please follow and like us:



Leave a Comment

Your email address will not be published. Required fields are marked *