Helping you build a better website
(and other interesting web stuff)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
Silva Web Designs - Blog

CSS/jQuery – How to add a custom Back to top Icon

The Back to top link allows users to smoothly scroll back to the top of the page. It’s a little detail which enhances navigation experience on website with long pages.

How to add a custom back (scroll) top top icon?

Firstly, within your footer, add the following HTML:-


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

Then add the following CSS:-


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

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


/* Back to Top */

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

jQuery('.back-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.

Any difficulties, just ask away in the comments!

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

Join the discussion