<scroll-top>

A custom element that scrolls to the top of the page. The element is not visible until the user scrolls down a specified amount of pixels.

Source code & documentation

Demo

for the <scroll-top> element to be visible.

Source code

Include the following code in your HTML file to use the <scroll-top> element and customize it to your needs.

HTML

Include the element in your HTML file. Customize the behavior of the element by setting the visible-after, top-offset, and smooth-scrolling attributes.

<scroll-top visible-after="150px" smooth-scrolling aria-label="Scroll to top">
  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="24" height="24" aria-hidden="true">
    <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="48" d="M112 328l144-144 144 144"></path>
  </svg>
</scroll-top>

CSS

Customize the styling of the component using the ::part pseudo-element.

scroll-top::part(button) {
  width: 45px;
  height: 45px;
  border: none;
  border-radius: 50%;
  background-color: #0d6efd;
  color: #ffffff;
  transition: transform 0.3s ease-in-out,
    visibility 0.3s ease-in-out,
    opacity 0.3s ease-in-out;
}

scroll-top::part(button):hover {
  background-color: #0b5ed7;
  border-color: #0a58ca;
}

scroll-top::part(button):focus-visible {
  outline: 2px solid #0096bfab;
}

scroll-top::part(button button--hidden) {
  transform: translateY(calc(100% + 16px));
}

JavaScript

Listen for the scroll-top:visibility-change event to know when the element becomes visible or hidden.

const scrollTopEl = document.querySelector('scroll-top');

scrollTopEl.addEventListener('scroll-top:visibility-change', evt => {
  console.log('event.detail ->', evt.detail);
});

License

The MIT License (MIT)