I was recently tasked with creating one of those ‘back to top’ scrolly buttons in a Squarespace site. I built a vanilla HTML prototype, which worked across all browsers, within like an hour.
However, upon migrating my little script to Squarespace, I found myself cursing a blue streak when I could get it to work in Chrome, but nowhere else. For anyone who encounters the same fate – it turns out the problem was how I was calling the scrollTop function – Firefox & IE do not like $(‘body’), document.body or document.documentElement on Squarespace (please tweet at me if you have found exceptions to this, or know why it happened).
In the end, here’s what worked for me, cross-browser. First, use the header code injection block to include a jQuery CDN:
JS (injected into the footer):
window.onload = function(){ window.onscroll = function() {scrollFunction()}; //fires the animation on scroll function scrollFunction() { if (document.body.scrollTop > 200) { //button appears once you scroll down 200px. To alter the appearance point, change the # $('#backToTop').addClass('button-visible'); //toggles the class that holds the CSS animations } else { $('#backToTop').removeClass('button-visible'); } } var backToTop = $('#backToTop'); //button backToTop.on('click', function(){ //on click, animates to the top of the page $('html').animate({ scrollTop: 0 }, 'fast'); //so the scroll works in firefox $('body').animate({ scrollTop: 0 }, 'fast'); //so the scroll works in webkit return false; }); };
CSS(injected into the header):
.backToTop{ opacity: 0; -webkit-transition: opacity 0.25s ease-in; position: fixed; right: 0px; bottom: 30px; font-size: 2em; } .backToTop::before { position: fixed; content:"\2191"; opacity: 1; color: #9b1408; margin-left: 20px; } .backToTop::after { content:""; background-color: #aaa; opacity: 0.4; z-index:-999999; padding: 10px 30px; } .button-visible{ opacity: 1; -webkit-transition: opacity 0.25s ease-in; transition: opacity 0.25s ease-in; }
HTML (which I put in a code block in the footer):