JavaScript / jQuery 🏖️ All about Smooth Scrolling

Share on email
Share on twitter
Share on linkedin
Share on facebook
Smooth Scrolling article with Javascript and jQuery By @wpr0ck
Smooth Scrolling article with Javascript and jQuery By @wpr0ck
Smooth Scrolling article with Javascript and jQuery By @wpr0ck
Smooth Scrolling article with Javascript and jQuery By @wpr0ck
Share on twitter
Share on linkedin
Share on facebook
Share on whatsapp
Share on email

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

This process allows you to apply an animation to the scroll and 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 provides users of sites that use it with an additional reading comfort. Indeed, since the movement within the site via internal hypertext links is visible and understandable, the user is no longer "teleported", but is able to find himself instinctively. He knows if he arrives on a part that precedes or anticipates the link he 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 be performed over 1500 milliseconds. This execution time can be extended or shortened by changing this value.

Smooth scrolling on HTML links to anchors with jQuery

As a reminder, the hyperlinks to anchors are in the form of <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 smooth movement to a HTML element targeted. In the code below, I present you a JavaScript function scrollTo( target )which takes an element as a parameter jQuery and applies the Smooth Scroll effect to it. The example of using 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 end on a piece of JavaScript / jQuery code that allows you to scroll smoothly to the top of the page.

$(function() {
    /**
    * Smooth scrolling to the top of page
    **/
    $("html, body").animate({scrollTop : 0}, 1500);
});
Julien MA Jacob
WordPress Developer
Julien MA JACOB - WordPress Developer
Passionate about the web and programming with always many projects in mind
  Discussion of the article
Subscribe to the newsletter
Notify to
guest
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Ben

Super tuto!
Is it possible to switch from one anchor to another simply with scroll?

Julien JACOB

Hello Ben and thank you!

As for moving from one anchor to another in scroll, I'm not sure I fully understand the idea. If the scroll causes a scrolling to the next anchor, how do you scroll (and therefore read) the content between 2 anchors?

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

Loïc

Hello!
Great! Great!
How could I make sure 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! :)