In this tutorial, we’ll be adding a Scroll to Top button to the website. These steps will work for SquareSpace, WordPress and any other CMS.
See it in action here: https://billmuirhead.com
First, let’s add the button to the body of the page.
Get the identifier on your header element, it may be on the <nav> element on something similar which lives on the top of each page.
In this case we’re using #site-header where we have a div with id = site-header.
Be sure to add the code below to the body element in such a way that it will show on each page such as the header or footer.
<a class="to-the-top" href="#site-header"> <span class="to-the-top-long"> To the top <span class="arrow" aria-hidden="true">↑</span> </span><!-- .to-the-top-long --> <span class="to-the-top-short"> Up <span class="arrow" aria-hidden="true">↑</span> </span><!-- .to-the-top-short --> </a>
Next, let’s add the javascript/ Jquery to add the scroll to top functionality to the button. It will the button when we’re already at the top!
First, add the following Jquery script tag to the Footer section to make sure Jquery is enabled:
<script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>
Following that, add the Scroll to Top javascript code also to the Footer section immediately after the Jquery script above.
jQuery( document ).ready(function() { jQuery(window).bind('scroll', function() { wrap = jQuery('body'); scrollTop = jQuery(window).scrollTop(); distance = 50; console.log("slide height!"); if (scrollTop > distance) { wrap.addClass("fixed"); jQuery( ".to-the-top" ).show(); } else { wrap.removeClass("fixed"); jQuery( ".to-the-top" ).hide(); } }); jQuery( ".to-the-top" ).click(function() { document.body.scrollTop = 0; // For Safari document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera }); });