Kinsa | Pixels + Logic Blog

Scroll an Element Into View with Vanilla JavaScript

A click on the HTML element with the ID myButton will trigger a smooth scroll to the element with the ID myDestination using the JavaScript function Element: scrollIntoView():


  document.addEventListener('DOMContentLoaded', function () {
    document.querySelector('#myButton').addEventListener('click', function (event) {
      event.preventDefault();
      this.blur();
      const myDestination = document.querySelector('#myDestination');
      myDestination.scrollIntoView({'behavior': 'smooth'});
    });
  });

Feedback?

Email us at enquiries@kinsa.cc.

Found this useful?

We always appreciate a pint!