Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to scroll to an element

Short answer

scrollIntoView() scrolls the page so the element becomes visible. The option behavior: 'smooth' makes it smooth:

<button id="go">To the contacts</button>
<div style="height: 1200px"></div>
<h2 id="contacts">Contacts</h2>
<script>
  document.getElementById('go').addEventListener('click', () => {
    document.getElementById('contacts').scrollIntoView({ behavior: 'smooth', block: 'start' });
  });
</script>

To the top

window.scrollTo() scrolls to coordinates:

window.scrollTo({ top: 0, behavior: 'smooth' });

With a fixed header

A fixed header covers the beginning of the element. Calculate the position yourself and subtract the header height:

const headerHeight = document.querySelector('header').offsetHeight;
const top = target.getBoundingClientRect().top + window.scrollY - headerHeight;
 
window.scrollTo({ top, behavior: 'smooth' });

Common mistake

For links inside the page you often do not need JavaScript at all: one CSS rule makes all anchor links smooth, and scroll-margin-top handles the header:

<style>
  html { scroll-behavior: smooth; }
  section { scroll-margin-top: 80px; }
</style>
<a href="#prices">Prices</a>

Thanks for reading!

Donate to the site — we work hard for you.