How to Implement Smooth Scrolling in JavaScript

Smooth scrolling is a technique used in web development to create a smooth scrolling experience for users. Here's how to implement smooth scrolling in JavaScript .

How to Implement Smooth Scrolling in JavaScript Picture 1How to Implement Smooth Scrolling in JavaScript Picture 1

What is Smooth Scrolling?

Smooth scrolling is when a web page scrolls smoothly to the desired section, instead of jumping there immediately. This provides a comfortable & seamless scrolling experience for users.

Benefits of Smooth Scrolling

Smooth scrolling can improve a website's user experience in a number of ways:

  1. Enhance image quality by eliminating sudden scroll jumps, adding a luxurious look to the interface.
  2. Encourage user interaction through smooth, seamless scrolling.
  3. Make it easier for users to navigate, especially when dealing with long web pages or moving between different sections.

How to make smooth scrolling in JavaScript

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

HTML structure

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

 

 Smooth Scrolling Guide for Web Developers 

Section 1

Section 2

Section 3

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

CSS Styles

Next, apply some CSS to make the page look attractive and organized. Add the following code 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 link as a row of buttons and each section as a full height element. But note how clicking a link causes the browser to jump immediately to the corresponding section, without animation.

 

How to Implement Smooth Scrolling in JavaScript Picture 2How to Implement Smooth Scrolling in JavaScript Picture 2

Implemented in JavaScript

To add a smooth effect when you click on the anchor tag, use scrollIntoView() . The scrollIntoView() function, available in JavaScript of the Element class, allows you to scroll an element into the visible area of ​​the browser window.

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

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

document.addEventListener("DOMContentLoaded", makeLinksSmooth);

Next, define the makeLinksSmooth() function . Start by selecting the anchor tabs in the navigation, as you'll want to tweak their behavior. Then loop through 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 a smoothScroll() function that takes an event listener. Call preventDefault() to make sure the browser doesn't implement the default action when you click on the link. The following code will replace it.

Get the href value of the current anchor tag and store it in a variable. That value will be the ID of the target section, prefixed with ' # ', so use it to select the section's element via querySelector() . If targetElement is visible, run its scrollIntoView 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", }); } }

Now your finished web page 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 tweak specific aspects.

 

Scroll position adjustment

You can adjust the vertical position of the scroll using the block property of the settings argument. Use values ​​like 'start', 'center' or 'end' to specify the section of the target element to scroll to:

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

Add Acceleration Effect

Apply an acceleration effect to the scroll animation to create a more natural and visually appealing transition. Acceleration functions such as ease-in, ease-out or custom cube curves can control the acceleration & deceleration of the scrolling motion. You can use a custom time locator with the CSS scroll-behavior property or a JavaScript library like 'smooth-scroll' to achieve the same result.

/* CSS để áp dụng hiệu ứng gia tốc */ html { scroll-behavior: smooth; /* Tùy biến gia tốc cubic-bezier */ scroll-behavior: cubic-bezier(0.42, 0, 0.58, 1); }

Ensure that the smooth scrolling implementation works consistently across different browsers. Check and correct any errors or inconsistencies that may arise.

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

How to Implement Smooth Scrolling in JavaScript Picture 3How to Implement Smooth Scrolling in JavaScript Picture 3

Smooth scrolling adds subtle beauty and enhances the user experience by creating eye-catching, smooth scrolling effects. Just by following the steps above, web developers can easily implement smooth scrolling using JavaScript.

5 ★ | 1 Vote