Как прокрутить страницу к элементу
Короткий ответ
scrollIntoView() прокручивает страницу так, чтобы элемент стал виден. Параметр behavior: '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>Наверх
window.scrollTo() прокручивает к координатам:
window.scrollTo({ top: 0, behavior: 'smooth' });С фиксированной шапкой
Фиксированная шапка закрывает начало элемента. Вычислите позицию сами и вычтите высоту шапки:
const headerHeight = document.querySelector('header').offsetHeight;
const top = target.getBoundingClientRect().top + window.scrollY - headerHeight;
window.scrollTo({ top, behavior: 'smooth' });Частая ошибка
Для ссылок внутри страницы JavaScript часто не нужен вовсе: одно CSS-правило делает плавными все якорные ссылки, а scroll-margin-top учитывает шапку:
<style>
html { scroll-behavior: smooth; }
section { scroll-margin-top: 80px; }
</style>
<a href="#prices">Prices</a>