JAVASCRIPT

Smoothly Scroll to Any DOM Element on the Page

Implement smooth scrolling behavior in JavaScript to programmatically navigate the user to a specific DOM element's position on the page.

// HTML Structure
/*
<style>
  body { height: 200vh; margin: 0; padding: 20px; font-family: sans-serif; }
  #targetSection {
    margin-top: 100vh; /* Push it down the page */
    padding: 50px;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    text-align: center;
  }
  #scrollToTargetBtn {
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 10px 15px;
    background-color: #28a745;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    z-index: 999;
  }
</style>
<button id="scrollToTargetBtn">Scroll to Target Section</button>
<p>Scroll down to see the target...</p>
<div id="targetSection">
  <h2>This is the Target Section</h2>
  <p>You can scroll to this element smoothly.</p>
</div>
*/

const scrollToTargetBtn = document.getElementById('scrollToTargetBtn');
const targetSection = document.getElementById('targetSection');

if (scrollToTargetBtn && targetSection) {
  scrollToTargetBtn.addEventListener('click', () => {
    targetSection.scrollIntoView({
      behavior: 'smooth', // Makes the scroll animation smooth
      block: 'start',     // Aligns the top of the element to the top of the viewport
      inline: 'nearest'   // Aligns the element horizontally as needed
    });
    console.log('Smoothly scrolled to the target section.');
  });
}
How it works: This snippet demonstrates how to programmatically scroll to a specific DOM element with a smooth animation effect. The `Element.scrollIntoView()` method is used, with the `behavior: 'smooth'` option enabling the animated scroll. Other options like `block` and `inline` allow precise control over how the element is positioned within the viewport after scrolling. This is highly useful for navigation, "back to top" buttons, or highlighting specific content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs