JavaScript / jQuery 🏖️ All about Smooth Scrolling

Share on twitter
Share on linkedin
Share on facebook
Share on whatsapp
Share on email
Share on twitter
Share on linkedin
Share on facebook
Share on whatsapp
Share on email

In this article we see how to use Smooth Scrolling, also called soft or fluid scrolling, in JavaScript and jQuery.

This process allows to apply an animation to the scroll and to slow down the scrolling to an element targeted by an anchor when clicking on a link, by a jQuery selector or to the top of the page.

This simple animation brings to the users of the sites that use it an additional reading comfort. Indeed, as the movement within the site by means of internal hypertext links is done in a visible and understandable way, the user no longer finds himself "teleported", but is able to find himself instinctively. He knows if he arrives on a part that precedes or precedes the link he has clicked on, as well as the distance that separates him from it.

In the different use cases presented here, the Smooth Scrolling effect is set to 1500 milliseconds. It is possible to lengthen or shorten this execution time by changing this value.

Smooth scrolling on HTML links to anchors with jQuery

As a reminder hyperlinks to anchors are in the form <a href="#my-id">Link to anchor</a> and point to elements HTML identified by their ID, for example <h2 id="my-id">My destination</h2>. Once added to your site, the code below will apply this Smooth Scroll effect automatically when you click on a link pointing to an anchor on the current page.

$(function() {
    /**
    * Smooth scrolling to page anchor on click
    **/
    $("a[href*='#']:not([href='#'])").click(function() {
        if (
            location.hostname == this.hostname
            && this.pathname.replace(/^\//,"") == location.pathname.replace(/^\//,"")
        ) {
            var anchor = $(this.hash);
            anchor = anchor.length ? anchor : $("[name=" + this.hash.slice(1) +"]");
            if ( anchor.length ) {
                $("html, body").animate( { scrollTop: anchor.offset().top }, 1500);
            }
        }
    });
});

Smooth scrolling to an HTML element with jQuery

This function, which takes a jQuery selector in parameter, allows a fluid movement to a HTML element targeted. In the code below, I present you a JavaScript function scrollTo( target )which takes in parameter an element jQuery and apply the Smooth Scroll effect to it. The example use of the function applies this effect to the element with the ID my-id.

$(function() {
    /**
    * Smooth scrolling to a specific element 
    **/
    function scrollTo( target ) {
        if( target.length ) {
            $("html, body").stop().animate( { scrollTop: target.offset().top }, 1500);
        }
    }

    // exemple
    scrollTo( $("#mon-id") );
});

Smooth scrolling to the top of the page with jQuery

In order to go around the subject, I suggest you finish on a piece of JavaScript / jQuery code that allows a smooth scrolling to the top of the page.

$(function() {
    /**
    * Smooth scrolling to the top of page
    **/
    $("html, body").animate({scrollTop : 0}, 1500);
});
Julien .MA Jacob
Developer WordPress
Julien MA Jacob - Developer WordPress
🧙♂️ Passionate about the web and programming with always lots of projects in mind 👨💻 | About page
  Discussion of the article
Subscribe to our newsletter
Notify of
guest
3 Comments
most popular
latest oldest
Inline Feedbacks
View all comments
Ben

Great tutorial!
Is it possible to switch from one anchor to another simply with the scroll?

Julien JACOB

Hello Ben and thank you!

As far as moving from anchor to scroll, I'm not sure I get the idea. If the scroll scrolls to the next anchor, how do you scroll (and therefore read) the content between 2 anchors?

But since it's possible to list anchors with their positions, to know the user's position on the page, to intercept scroll down and scroll up events and finally to scroll to an anchor, then I guess it's possible with the right JS function :)

Loïc

Hello!
Oh, great!
How can I make it so that when I click on a link that sends to an anchor on another page, it loads and scrolls to the anchor?

Thank you in advance! :)