how to smooth scroll in javascript

How to Smooth Scroll in JavaScript

If you're looking to add a smooth scrolling effect to your webpage, JavaScript can help. With the following code, you can ensure that your webpage scrolls smoothly and seamlessly:

Step 1: Add Smooth Scroll JavaScript Code

First, you need to add the smooth scroll JavaScript code. Here's how:


    // Select all links with hashes
    $('a[href*="#"]')
      // Remove links that don't actually link to anything
      .not('[href="#"]')
      .not('[href="#0"]')
      .click(function(event) {
        // On-page links
        if (
          location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
          && 
          location.hostname == this.hostname
        ) {
          // Figure out element to scroll to
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
          // Does a scroll target exist?
          if (target.length) {
            // Only prevent default if animation is actually gonna happen
            event.preventDefault();
            $('html, body').animate({
              scrollTop: target.offset().top
            }, 1000, function() {
              // Callback after animation
              // Must change focus!
              var $target = $(target);
              $target.focus();
              if ($target.is(":focus")) { // Checking if the target was focused
                return false;
              } else {
                $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
                $target.focus(); // Set focus again
              };
            });
          }
        }
      });

Step 2: Add CSS Styles for Smooth Scrolling

Now that you've added the JavaScript code, you need to add CSS styles for smooth scrolling. Here's how:


    html {
      scroll-behavior: smooth;
    }

    /* Optional styles for smooth scrolling links */
    a {
      transition: all 0.3s ease-in-out;
    }

    a:hover {
      color: #6d4c41;
    }

Step 3: Test Smooth Scrolling on Your Webpage

Once you've added the JavaScript code and CSS styles, test smooth scrolling on your webpage to ensure it's working properly. You can do this by clicking on any internal links on your webpage and seeing if the page scrolls smoothly to the target destination.

That's it! With these simple steps, you can add smooth scrolling to your webpage and provide a better user experience for your visitors.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe