Loading...

Back To The Future In Three Lines of Javascript

Emilian F. Published on 12 September, 2014

You can ignore the blatant movie reference in the title, there is no way you can time travel in three lines of code. It would take at least six and a DeLorean.

Putting that aside, I will show you how to add a "back to the top" feature to your store in three lines of Javascript. For the uninitiated, such a script takes you to the top of a page when you click on an link in the footer. This feature is popular and has spawned many needlessly complex plugins that can be replaced with the few lines of code below. You don't need any external plugins outside of jQuery which you already have as it comes standard with all Bigcommerce themes.

Follow the instructions below to install the script and take the time to pat yourself on the back for not installing a bloated plugin in your store.

Instructions

  1. Login to your control panel and navigate to Design > Themes > Edit HTML & CSS and open the Footer.html file.

  2. Add the following code to the file, inside of the #Footer element:

    
    <a href="#" id="backtoTop">^UP</a>
    
    

    This will serve as the link that your visitors will click to reach the top of the page. This screen shot shows the placement of the code inside of the Footer.html file:

  3. Now add these three magical lines of Javascript at the very bottom of the file:

    
    <script type="text/javascript">
    $('#backtoTop').click(function(){
    $("body").animate({ scrollTop: 0 }, 600); return false;
    });
    </script>​​​​
    
    

    The final file should look like this:

  4. Press Save in the top left corner.

How Does It Work?

A click on the link element in the footer will take the visitor to the top of the page. To make the link stand out you can use CSS to inscrease the font size, or change the background color. You can even use a different element such as a span or div as long as you keep the same #backtoTop ID. If you want to scroll faster then change the 600 milliseconds to a smaller number such as 300.

Troubleshooting

If nothing happens when you click the link ... then try to move the Javascript code after the element in the page. The issue is caused by the code running before the element is displayed on the page. The alternative is to use this code:


<script type="text/javascript">
$(document).ready(function(){
$('#backtoTop').click(function(){
$("body").animate({ scrollTop: 0 }, 600); return false;
});
});
</script>​​​​

That way the code will run after the browser loads all of the elements on the page.

Emilian F. Published on 12 September, 2014