WordPress / Web Development Tutorials
(Best WordPress Tutorials)

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 that enhances the navigation experience on a 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-image: url(../img/back-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:-


/* 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 and various other CMS frameworks. If you need responsive design, SEO, speed optimisation or anything else in the world of digital, you can contact Silva Web Designs here; [email protected]

It’s good to share

Join the discussion