Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.

Smooth scrolling is a technique used in web development to create a fluid scrolling experience for users. It enhances the navigation within a webpage by animating the scroll movement instead of the default abrupt jump.

This comprehensive guide for web developers will help you implement smooth scrolling using JavaScript.

Understanding Smooth Scrolling

Smooth scrolling is when a webpage scrolls smoothly to the desired section, instead of jumping there instantly. This makes the scrolling experience more pleasant and seamless for the user.

The Benefits of Smooth Scrolling

Smooth scrolling can improve the user experience of a webpage in several ways:

  • It enhances the visual appeal by eliminating abrupt and jarring scroll jumps, adding a touch of elegance.
  • It encourages user engagement by providing a fluid and seamless scrolling experience. This, in turn, motivates users to explore the content further.
  • Lastly, smooth scrolling makes navigation easier for users, particularly when dealing with lengthy web pages or moving between different sections.

Implementing Smooth Scrolling in JavaScript

To implement smooth scrolling, you can modify the default scroll behavior using JavaScript.

HTML Structure

First, create the necessary markup elements for the different viewports and the navigation to scroll between them.

 <!DOCTYPE html> 
<html lang="en">

<head>
 <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="./style.css" />
  <title>Smooth Scrolling Guide for Web Developers</title>
</head>

<body>
  <nav>
    <ul>
      <li><a href="#section1">Section 1</a></li>
      <li><a href="#section2">Section 2</a></li>
      <li><a href="#section3">Section 3</a></li>
    </ul>
  </nav>

  <section id="section1">
    <h2>Section 1</h2>
  </section>

  <section id="section2">
    <h2>Section 2</h2>
  </section>

  <section id="section3">
    <h2>Section 3</h2>
  </section>

  <script src="./script.js"></script>
</body>

</html>

This HTML consists of a navigation bar holding three anchor tags. The href attribute of each anchor specifies the target section's unique identifier (e.g. section1, section2, section3). This ensures that each link you click on navigates to the corresponding target element.

CSS Styling

Next, apply some CSS to make the page visibly appealing and organized. Add the following to style.css:

 * {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

nav {
  background: #fff;
  box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.25);
  position: sticky;
  top: 0;
  padding: 30px;
}

nav ul {
  display: flex;
  gap: 10px;
  justify-content: center;
}

nav ul li {
  list-style: none;
}

nav ul li a {
  border-radius: 5px;
  border: 1.5px solid #909090;
  text-decoration: none;
  color: #333;
  padding: 10px 20px;
}

section {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

This will render the links as a row of buttons and each section as a full-height element. But notice how clicking a link causes the browser to instantly jump to the corresponding section, with no animation.

JavaScript Implementation

In other to add a smooth animation when you click on an anchor tag, use the scrollIntoView() method. The scrollIntoView() method is a built-in JavaScript method of the Element class that allows you to scroll an element into the visible area of the browser window.

When you call this method, the browser adjusts the scroll position of the element's container (such as the window or a scrollable container) to make the element visible.

Add your JavaScript code to the script.js file. Start by listening for the DOMContentLoaded event to fire before doing anything else. This ensures the callback only runs when the DOM is fully loaded and is ready to manipulate.

 document.addEventListener("DOMContentLoaded", makeLinksSmooth); 

Next, define the makeLinksSmooth() function. Start by selecting the anchor tags in the navigation, since you’ll want to modify their behavior. Then, iterate over each link, and add an event listener for its click event.

 function makeLinksSmooth() { 
  const navLinks = document.querySelectorAll("nav a");

  navLinks.forEach((link) => {
    link.addEventListener("click", smoothScroll);
  });
}

Finally, define the smoothScroll() function which takes an event listener object. Call preventDefault() to ensure the browser does not perform its default action when you click the link. The code that follows will replace it.

Grab the href value of the current anchor tag and store it in a variable. That value should be the ID of the target section, with the prefix "#", so use it to select the section’s element via querySelector(). If the targertElement is present, run its scrollIntoView method and pass the "smooth" behavior in an object parameter to complete the effect.

 function smoothScroll(e) {
  e.preventDefault();
  const targetId = this.getAttribute("href");
  const targetElement = document.querySelector(targetId);

  if (targetElement) {
    targetElement.scrollIntoView({ behavior: "smooth", });
  }
}

With that, your finished webpage will scroll smoothly to each section when you click on a link:

Fine-Tuning Smooth Scrolling

To further enhance the smooth-scrolling experience, you can fine-tune certain aspects.

Adjusting Scroll Position

You can adjust the vertical position of the scroll using the block property of the settings argument. Use values such as "start," "center," or "end" to identify the part of the target element to scroll to:

 targetElement.scrollIntoView({ behavior: "smooth", block: "end" }); 

Adding Easing Effects

Apply easing effects to the scroll animation to create a more natural and visually appealing transition. Easing functions such as ease-in, ease-out, or custom cubic-bezier curves can control the scroll movement's acceleration and deceleration. You can use a custom timing function with the scroll-behavior CSS property or a JavaScript library such as "smooth-scroll" to achieve the same result.

 /* CSS to apply easing effect */ 
html {
  scroll-behavior: smooth;

  /* Custom cubic-bezier easing */
  scroll-behavior: cubic-bezier(0.42, 0, 0.58, 1);
}

Ensure that your smooth scrolling implementation works consistently across different browsers. Test and handle any browser-specific quirks or inconsistencies that may arise.

You can use a website like Can I Use to test browser support when building. Consider using a JavaScript library or polyfill to ensure cross-browser compatibility and provide a seamless experience for all users.

Showing browser suport for javascript methods

Elevating User Experience With Smooth Scrolling in JavaScript

Smooth scrolling adds a touch of elegance and enhances the user experience by creating a fluid and visually pleasing scrolling effect. By following the steps outlined in this guide, web developers can implement smooth scrolling using JavaScript.

Fine-tuning the scrolling behavior, adding easing effects, and ensuring cross-browser compatibility will further enhance the smooth scrolling experience, making your web pages more engaging and enjoyable to navigate.