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 applies an animation to the scroll and slows down the scroll 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 additional reading comfort. Indeed, the movement within the site by means of internal hypertext links is done in a visible and comprehensible way, the user does not find himself "teleported", but is able to find himself instinctively. He knows whether he is arriving at a part that precedes or precedes the link he has clicked on, as well as the distance that separates him from the latter.

In the various use cases presented here, the Smooth Scrolling effect is set to run for 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 for a smooth move 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 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 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 just by scrolling?

Julien JACOB

Hello Ben and thank you!

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

But since it is possible to list 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 guess it is possible with the right JS function :)

Loïc

Hello!
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?

Thanks in advance! :)