JAVASCRIPT

Implement Smooth Scroll to an Element

Guide users smoothly to specific sections or elements on a web page using JavaScript's `scrollIntoView()` method. Enhance user experience for navigation or 'back to top' features.

const scrollToTopButton = document.getElementById('scrollToTop');
const targetSection = document.getElementById('sectionToScrollTo');

if (scrollToTopButton && targetSection) {
  scrollToTopButton.addEventListener('click', () => {
    // Option 1: Basic smooth scroll
    targetSection.scrollIntoView({
      behavior: 'smooth',
      block: 'start' // 'start', 'center', 'end', or 'nearest'
    });

    // Option 2: Scroll to top of the page smoothly (alternative)
    // window.scrollTo({
    //   top: 0,
    //   behavior: 'smooth'
    // });
  });
}

// Example for a dynamic element that might appear later
const dynamicScrollButton = document.getElementById('dynamicScrollBtn');
if (dynamicScrollButton) {
    dynamicScrollButton.addEventListener('click', () => {
        const newElement = document.createElement('h2');
        newElement.id = 'dynamicallyCreatedSection';
        newElement.textContent = 'This is a Dynamic Section!';
        newElement.style.marginTop = '2000px'; // Push it far down for scrolling demo
        document.body.appendChild(newElement);

        newElement.scrollIntoView({
            behavior: 'smooth',
            block: 'center'
        });
    });
}
How it works: This snippet demonstrates how to programmatically scroll to a specific HTML element using `element.scrollIntoView()`. By setting `behavior: 'smooth'`, the browser animates the scroll, providing a better user experience than an abrupt jump. The `block` option specifies the vertical alignment of the target element within the viewport. This is ideal for 'back to top' buttons or navigating to specific content sections dynamically.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs