In this article we will show you how to create a back to top button or link on your WordPress website. Back to top button can be useful to visitors reading long articles or browsing large pages. After reading a long article, scrolling browser window back to top can be a little frustrating and not very user friendly at all. Your visitors shouldn’t have to scroll all the way to the top. Creating a good user experience on your website is very important to keep people on the page.
Although there are many WordPress plugins available to add this feature on your website but it’s fairly very easy to create a back to top button. And you shouldn’t want to use a plugin when you can create sometime with couple of lines of code. So here is how to create the back to top button without using a plugin or editing core WordPress files. We will use smooth scrolling effect with jQuery for better user experience to avoid fast jumping.
First, we need to create the link. For that paste this code in your theme functions.php file.
// add back to top button in wordpress footer
function wcs_add_back_to_top() {
echo '<a id="toTop" href="#">Back to Top ↑</a>';
}
add_action( 'wp_footer', 'wcs_add_back_to_top' );
And now we can style the button with the following CSS.
/* css styles for back to top button */
#toTop {
padding: 10px 20px;
font-weight: bold;
color: #FFF;
text-decoration: none;
position: fixed;
bottom: 40px;
right: 40px;
display: none;
background: rgba(0, 0, 0, 0.5);
}
And finally copy and paste the following in the Javascript file to add the Javascript functionality.
jQuery(document).ready(function($) {
$(window).scroll(function(){
if ( $(this).scrollTop() > 100 ) {
$('#toTop').fadeIn();
} else {
$('#toTop').fadeOut();
}
});
$('#toTop').click(function(){
$('html, body').animate( {scrollTop : 0}, 800 );
return false;
});
});
With only three easy steps, now we have a back or scroll to top link with smooth scrolling effect.