JAVASCRIPT

Scroll to an Element Smoothly

Enhance user experience by programmatically scrolling to any specific element on the page with a smooth animation using native JavaScript DOM methods.

<style>
  body { height: 200vh; margin: 0; padding: 0; }
  #targetElement { 
    margin-top: 150vh; 
    padding: 20px; 
    background-color: lightblue; 
    border: 2px solid blue; 
    width: 200px; 
    text-align: center;
  }
  button { position: fixed; top: 10px; left: 10px; padding: 10px; }
</style>

<button id="scrollToTargetBtn">Scroll to Target</button>
<div id="targetElement">I am the target element!</div>

<script>
  const scrollToTargetBtn = document.getElementById('scrollToTargetBtn');
  const targetElement = document.getElementById('targetElement');

  scrollToTargetBtn.addEventListener('click', () => {
    // Scroll the targetElement into view with smooth behavior
    targetElement.scrollIntoView({
      behavior: 'smooth',
      block: 'start' // Aligns the top of the element to the top of the scroll area
    });
  });
</script>
How it works: The `scrollIntoView()` method on an element provides a simple way to programmatically scroll an element into the visible area of the browser window. By passing an options object with `behavior: 'smooth'`, you instruct the browser to animate the scroll, providing a much better user experience than an instantaneous jump. The `block` option specifies the vertical alignment of the element within the scrollable area.

Need help integrating this into your project?

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

Hire DigitalCodeLabs