PROJECTS NOTES HOME

Scroll to top button

Might be useful when you have a large document and the table of contents or navigation is not sticky and you need a quick way to get back to the top of the page.

1 html

Add this to postamble(footer, or bottom of your html page):

Remove the emacs formatting(if using outside of Emacs), the \'s especially.

<button onclick=\"topFunction()\" id=\"myBtn\" title=\"Go to top\">Top</button>

2 css

/* scroll to the top button */

#myBtn {
  display: none;
  position: fixed;
  bottom: 20px;
  right: 30px;
  z-index: 99;
  font-size: 10px;
  border: none;
  outline: none;
  background-color: #6264f0;
  color: white;
  font-weight: 800;
  cursor: pointer;
  padding: 8px;
  opacity: 0.5;
  border-radius: 4px;
}

#myBtn:hover {
  background-color: #555;
}

3 js

// scroll to the top button

// Get the button
let mybutton = document.getElementById("myBtn");

// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    mybutton.style.display = "block";
  } else {
    mybutton.style.display = "none";
  }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}