A simple method to insert a 'back to top' button on a web page using javascript to detect if the the page is scrolled down (to show it) or scrolled up (to hide it).
I use pure CSS to draw a circle (a border with radius 50%) around a rotated ❮ character. The border is set to a light colour, while its outline is set to dark colour and likewise the arrow is a light colour with a 'webkit-text-stroke' dark colour.
First, here's the html to include the button on the page (a file in _includes)...
View code
It is included by a jekyll tag in the page layout file...
View code
And the CSS..
View code
The 'div height' line helps to keep the arrow in the center of the circle, rather than sitting at the bottom.
And of course, the script....
So what happens?
the 'backtotopBtn' variable is set to false at page load, and if it is false and page scrolls a full screen ht, the fn 'showBtn' is called
the fn adds the class 'show-totop' to the button to trigger display, then sets the 'backtotopBtn' variable to true
with 'backtotopBtn' true the fn will not be called again while scrolling down
if page is scrolled up to the top screen ht, the fn 'hideBtn' is called and 'backtotopBtn' variable is set to false again, for next time!
and of course the onClick fn of the button itself, scrolls to top with a smooth effect.