Skip to content

Scroll to top button to quickly jump to the top of the page #1126

@choldgraf

Description

@choldgraf

A common feature in many websites with a lot of content is to have a "scroll to top" button that pops up when two conditions are met.

  1. The person has already scrolled down the page by some amount.
  2. The person starts to scroll upward.

I think this theme should support a similar kind of pattern, since many pages in the sphinx/python ecosystem have very long content. cc @trallard in case this also has accessibility implications.

Inspiration

For example:

mkdocs material:

chrome_OXhehrrbpP

furo:

chrome_2QgmBefVhS

Implementation

The way I've seen this done is to use a little "helper pixel" that is used to trigger a javascript event to detect condition 1, and then use a "scroll up" event to trigger condition 2.

For example, in the book theme we have something like this. Here is the little empty pixel div:

https://github.com/executablebooks/sphinx-book-theme/blob/cda3bb5753669c095903986cc0a649ff400fcef1/src/sphinx_book_theme/theme/sphinx_book_theme/layout.html#L4-L6

Here is the styling to make it invisible:

https://github.com/executablebooks/sphinx-book-theme/blob/cda3bb5753669c095903986cc0a649ff400fcef1/src/sphinx_book_theme/assets/styles/base/_base.scss#L15

and here we set javascript to use an IntersectionObserver event that triggers when the empty div scrolls off screen, and it adds a class called scrolled to the page's body when it is triggered:

https://github.com/executablebooks/sphinx-book-theme/blob/cda3bb5753669c095903986cc0a649ff400fcef1/src/sphinx_book_theme/assets/scripts/index.js#L105-L149

We could then add a "scroll up" event that would show the button if the body.scrolled class is present, and a "scroll down" event that would hide the button if it is shown.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions