Skip to content
the poor coder

how to smooth scroll in javascript

Poor Man
Published
Reading time
2 min read
On this page

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:

Text

    // 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:

Text

    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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC