JAVASCRIPT

Smooth Scroll to an HTML Element Programmatically

Implement smooth programmatic scrolling to any target element on a webpage, significantly enhancing user navigation and overall experience.

// HTML Structure:
// <button id="scrollToSectionBtn">Scroll to Section</button>
// <div style="height: 1000px; background-color: #f0f0f0;"></div>
// <section id="targetSection" style="padding: 50px; background-color: lightblue;">
//   <h2>Target Section</h2>
//   <p>This is the content you want to scroll to.</p>
// </section>
// <div style="height: 500px; background-color: #f0f0f0;"></div>

document.addEventListener('DOMContentLoaded', () => {
  const scrollToSectionBtn = document.getElementById('scrollToSectionBtn');
  const targetSection = document.getElementById('targetSection');

  if (scrollToSectionBtn && targetSection) {
    scrollToSectionBtn.addEventListener('click', () => {
      targetSection.scrollIntoView({
        behavior: 'smooth', // Enables smooth scrolling animation
        block: 'start'      // Aligns the top of the element to the top of the viewport
      });
      console.log('Scrolling to target section...');
    });
  }
});
How it works: This snippet demonstrates how to programmatically scroll to a specific HTML element with a smooth animation effect. By calling `scrollIntoView()` on a target element and passing an options object with `behavior: 'smooth'`, the browser animates the scroll, providing a better user experience than an instant jump. The `block: 'start'` option ensures that the top edge of the target element aligns with the top of the viewport when scrolling.

Need help integrating this into your project?

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

Hire DigitalCodeLabs