Menu Close

How to add a custom back(scroll) to top icon using css/jquery

backto-top

In this session, we are know about the Back to top link allows users to smoothly scroll back to the top of the page. It’s a little detail that enhances the navigation experience on a website with long pages.

How to add custom back(scroll) to top icon

First of all, within your footer, add the following HTML,

<a href="#" class="scroll-to-top"></a> 

Then add the following CSS:-

.scroll-to-top {
    display: none;
    background-image: url(../img/scroll-to-top.png); // Link this to your image
    background-repeat: no-repeat;
    position: fixed;
    height: 30px; // The height of the icon you added for the background
    width: 30px; // The width of the icon you added for the background
    background-size: 30px; // The height and width of the background image
    bottom: 30px;
    height: 30px;
    z-index: 999;
    } 

The magic behind it is adding jQuery to handle the fade in/out when the scroll point is further down the page. Add the following jQuery code:-

/* scroll to Top */

var offset = 220;
var duration = 500;
jQuery(window).scroll(function() {
	if (jQuery(this).scrollTop() &gt; offset) {
		jQuery('.scroll-to-top').fadeIn(duration);
	} else {
		jQuery('.scroll-to-top').fadeOut(duration);
	}
});

jQuery('.scroll-to-top').click(function(event) {
	event.preventDefault();
	jQuery('html, body').animate({scrollTop: 0}, duration);
	return false;
});	 

And there you have it, you now have an icon that appears on the bottom right-hand corner when you scroll down the page. Clicking this element will smoothly scroll back to the top of the page.

Remember to include the jQuery library and jQuery UI for this to work properly.

Posted in CSS, jQuery, Web Technologies

You can also read...