← Back to all snippets
JAVASCRIPT

Smoothly Scroll to Any Element with `scrollIntoView`

Enable smooth, programmatic scrolling to bring specific elements into the viewport using `element.scrollIntoView()`, enhancing user navigation and accessibility in web applications.

<style>
  body { height: 2000px; /* Make page scrollable */ }
  #targetElement { 
    margin-top: 1000px; 
    padding: 20px; 
    background-color: #f0f0f0; 
    border: 1px solid #ccc;
  }
  #targetElement2 { 
    margin-top: 500px; 
    height: 300px;
    padding: 20px; 
    background-color: #e0e0e0; 
    border: 1px solid #ccc;
  }
</style>

<button id="scrollToTarget">Scroll to First Target</button>
<button id="scrollToTarget2">Scroll to Second Target (smooth, center)</button>

<div style="height: 800px;">Spacer Content</div>
<div id="targetElement">I am the first target element!</div>
<div style="height: 400px;">More Spacer Content</div>
<div id="targetElement2">I am the second target element!</div>

<script>
  document.getElementById('scrollToTarget').addEventListener('click', () => {
    const target = document.getElementById('targetElement');
    target.scrollIntoView(); // Default: smooth behavior, block: 'start'
  });

  document.getElementById('scrollToTarget2').addEventListener('click', () => {
    const target = document.getElementById('targetElement2');
    target.scrollIntoView({
      behavior: 'smooth', // Enable smooth scrolling
      block: 'center',    // Align the top of the element to the center of the viewport
      inline: 'nearest'   // Align the element horizontally to the nearest edge
    });
  });
</script>
How it works: `element.scrollIntoView()` is a powerful method that scrolls the element on which it's called into the visible area of the browser window. This snippet demonstrates two uses: a basic call which defaults to 'smooth' behavior and 'block: start' (aligning the element's top to the viewport's top), and a more customized call using an options object. The options allow specifying `behavior: 'smooth'` for a gentle animation, and `block: 'center'` to position the element in the middle of the viewport, significantly improving user experience for navigation links, error messages, or 'back to top' buttons.

Need help integrating this into your project?

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

Hire DigitalCodeLabs