JAVASCRIPT

Programmatic Scrolling to Specific DOM Elements

Implement smooth, programmatic scrolling to bring any target DOM element into view using modern JavaScript's `scrollIntoView()` method with customizable options.

document.addEventListener('DOMContentLoaded', () => {
  const sections = document.querySelectorAll('.section');
  const navLinks = document.querySelectorAll('.nav-link');

  navLinks.forEach(link => {
    link.addEventListener('click', (event) => {
      event.preventDefault(); // Prevent default anchor jump
      const targetId = link.getAttribute('href').substring(1); // Get target ID from href
      const targetElement = document.getElementById(targetId);

      if (targetElement) {
        targetElement.scrollIntoView({
          behavior: 'smooth', // Smooth scrolling animation
          block: 'start'      // Align the top of the element with the top of the viewport
        });
      }
    });
  });

  // Example: Scroll to a specific section on page load after a delay
  // setTimeout(() => {
  //   const specificSection = document.getElementById('section3');
  //   if (specificSection) {
  //     specificSection.scrollIntoView({ behavior: 'smooth' });
  //   }
  // }, 2000);
});

/*
HTML structure for context:
<nav>
  <a href="#section1" class="nav-link">Go to Section 1</a>
  <a href="#section2" class="nav-link">Go to Section 2</a>
  <a href="#section3" class="nav-link">Go to Section 3</a>
</nav>
<div id="section1" class="section" style="height: 500px; background-color: #f8f8f8;"><h2>Section 1</h2></div>
<div id="section2" class="section" style="height: 500px; background-color: #e8e8e8;"><h2>Section 2</h2></div>
<div id="section3" class="section" style="height: 500px; background-color: #d8d8d8;"><h2>Section 3</h2></div>
<div id="section4" class="section" style="height: 500px; background-color: #c8c8c8;"><h2>Section 4</h2></div>
*/
How it works: The `Element.scrollIntoView()` method scrolls the element's parent container(s) to make the element visible to the user. It accepts an optional `options` object for more control. The `behavior: 'smooth'` option provides a visually pleasing animated scroll, while `behavior: 'auto'` (default) jumps instantly. The `block` option (`start`, `center`, `end`, `nearest`) specifies the vertical alignment of the element within the viewport. This snippet demonstrates its use for navigation, allowing users to smoothly jump to different sections of a long page.

Need help integrating this into your project?

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

Hire DigitalCodeLabs