Create a scroll effect when you navigate to an element

scroll effect

When you navigate to an element with a mouse click in the same page, in the usual case the browser quickly jumps directly to the element. But when there is a scrolling effect to the element, just like when you scroll to the required element manually using the mouse, then it looks good to the visitors eyes.

Lets take you to the way how this is done.

We will be wrapping the javascript code inside the jQuery document ready function so that the code is initialized once the DOM is loaded.

So we will add the jQuery library first


<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>

And then the code


$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 500, 'swing', function () {
            });
    });
});

This will create the scroll effect once you click on a button that navigates to an element in the same page.

Leave a Reply

Your email address will not be published.