How to Implement Smooth Scrolling in JavaScript
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:
- Enhance image quality by eliminating sudden scroll jumps, adding a luxurious look to the interface.
- Encourage user interaction through smooth, seamless scrolling.
- 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.
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.
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.
You should read it
- How to turn on and turn off smooth scrolling on Opera
- How to turn off smooth scrolling in Google Chrome
- Instructions for enabling Smooth Scrolling on Google Chrome
- How to create scrolling backgrounds in Pygame
- How to Implement Infinite Scrolling in Vue
- What is Infinite Scrolling and how does it work?
- How to take scrolling, long screen screenshots in Windows
- Instructions for scrolling TikTok videos automatically
- Why are websites scrolling vertically and not horizontal scrolling?
- How to enable two-finger scrolling on Windows laptop
- How to add a scrolling camera to PyGame
- How to Change Scrolling Speed on a Mac
Maybe you are interested
Turn off these visual effects to make Windows run smoother!
Tweaks to make Windows 11 run faster and smoother
How to smooth skin in Photoshop
3 Minimum, smooth GTA 5 playing configuration and max setting 2024
Learn about Steam Families: Tool to make game sharing smoother
How to download Genshin Impact for weak devices, play Genshin Impact smoothly on weak devices