Here at Future Studio, we have a table of contents with linked headlines next to a tutorial. We call this table of contents „Moonshoot“: it allows you to jump through the tutorial and visit individual sections.
Our moonshoot is sticky positioned and stays visible next to the tutorial when you scroll through the content. A pleasant experience for users is a smooth scroll when clicking on one of the links in the moonshoot.
This tutorial shows you how to smoothly scroll to an HTML element on your website.
JavaScript Series Overview
- Get the Current URL
- Get URL Query Parameters
- How to Smooth Scroll to an HTML Element
- Sort a Set
- New, Immutable Array Methods
- Detect Network Error
- Create Array from AsyncIterable
- Using the new Array Grouping Methods
- Test for LocalStorage Support
- Get Battery Status
- Detect If a Device Battery Is Charging (Coming soon)
Smoothly Scroll to an HTML Element
All browsers allow you to jump to an element on your website identified by a unique ID. You can use an anchor tag with an href
that starts with a #
to jump to that element. By default, a click on the anchor tag makes the browser jump to the section carrying the ID of the href:
<a href="#a-unique-id-on-this-page" data-toc-button>Jump to the Section</a>
<section id="a-unique-id-on-this-page">
<h2>Smoothly Scroll to an HTML Element</h2>
<p>A text for this section</p>
</section>
You can change the scroll behavior to smoothly scroll to a section when clicking on a link.
Use the element.scrollIntoView
method to apply the position change and also add the behavior: 'smooth'
option for smooth scroll behavior:
document.querySelectorAll('[data-toc-button]').forEach(button => {
button.addEventListener('click', () => {
const section = document.getElementById(button.href)
if (section) {
section.scrollIntoView({ behavior: 'smooth' })
}
});
})
All modern browsers support a smooth scroll to an element.
Enjoy!