In many websites having long contents we have seen a "Back To Top" or "Scroll To Top" button when a click 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 article we will implement the same feature in one of the easiest possible ways. To integrate this feature, we need a little HTML, some CSS for styling and a couple of lines of jQuery code. Using the following 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.
<body>
<h1>
Back To Top Demo by Nitesh Luharuka</h1>
<div style="height: 1000px">
</div>
<span id="back-to-top">
<img src='images/up-arrow.png' /></span>
</body>
If you notice in the preceding, 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 an 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.
#back-to-top
{
position: fixed;
bottom: 30px;
top: 350px;
}
#back-to-top img
{
cursor: pointer;
}
Now, our HTML is ready and for adding the code to the image, we will write the following code in our <head> section of the page. If you've already included jQuery, then you do not need to include the jQuery file again in your project.
<script type="text/javascript">
$(document).ready(function () {
//Hide Back to top button
$("#back-to-top").hide();
$(window).scroll(function () {
if ($(window).scrollTop() > 200) {
$('#back-to-top').fadeIn();
} else {
$('#back-to-top').fadeOut();
}
});
$('#back-to-top img').click(function () {
$('body').animate({
scrollTop: 0
}, 1000);
});
});
</script>
In the code above, we have done a few things. Let me explain them one by one:
- First, 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.
I hope you like this article. Keep learning and sharing!