May 6, 2014 by Nitesh

How To Implement Back To Top Feature in Html/Asp.Net/PhP


In many websites having long contents we have seen a “Back To Top” or “Scroll To Top” button when clicked takes you to the top of the webpage. We see this kind of feature normally on the product listing pages of e-commerce websites. Today in this post we will implement the same feature in one of the easiest possible way. To integrate this feature, we need a little HTML, some CSSĀ  for styling and a couple of lines of jQuery code. Using the below method, you can integrate the “Back To Top” feature on your website irrespective of the programming language of your website, be it ASP.Net or PhP.

To start with, we will create a HTML page with the following content in the <body> section.

<h1>Back To Top Demo by Nitesh Luharuka</h1>
<div style="height:1000px"></div>
<span id="back-to-top"><img src="http://www.niteshluharuka.com/how-to-implement-back-to-top-feature-in-htmlasp-netphp/images/up-arrow.png"/></span>

If you notice the above, we have added a div with some height to test our feature. At the end, we have added a “<span>” tag having an image of upward arrow. This arrow will be shown once the user starts scrolling down. To position the image, we will use a bit of CSS. Here’s the CSS for the button. You need to add this in the head section of your page.

     position: fixed;
     bottom: 30px;
     top: 350px;
#back-to-top img

Now, our HTML is ready and for adding the code to the image, we will write the below code in our <head> section of the page. If you’ve already included jQuery, then you do not need to include jQuery file again in your project.

<script type="text/javascript">
        $(document).ready(function () {
            //Hide Back to top button

            $(window).scroll(function () {                
                if ($(window).scrollTop() > 200) {
                } else {
            $('#back-to-top img').click(function () {
                    scrollTop: 0
                }, 1000);

In the code above, we have done few things. Let me explain them one by one

  • 1st of all, we hide the image when the document loads.
  • In the scroll() event handler, we have ensured that as the user starts scrolling and has scrolled 200px (you can change this), the “Back To Top” image becomes visible to the user.
  • In the click() event handler of the button, we send the user back to the top of the page using a nice animation effect of jQuery.

Hope you like this post. Keep learning and sharing!


Support us!

If you like this site please help and make click on any of these buttons!

Powered by WordPress Popup