-->

Bootstrap - Scrollspy Part 2: Adding Smooth Scrolling

Smooth scrolling enhances usability by animating the scroll action to the target section when a navigation link is clicked.

Examples and Explanation

CSS for Smooth Scrolling

html {

    scroll-behavior: smooth;

}

Explanation: Adding scroll-behavior: smooth in CSS ensures a seamless transition between sections.

JavaScript for Enhanced Smooth Scrolling

document.querySelectorAll('a[href^="#"]').forEach(anchor => {

    anchor.addEventListener('click', function (e) {

        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({

            behavior: 'smooth'

        });

    });

});

Explanation: This script provides cross-browser compatibility for smooth scrolling.

Enhanced Smooth Scrolling Example Combine Scrollspy with smooth scrolling for a polished navigation experience.