Skip to main content
Snippets

Simple Back to Top Button for WordPress

By March 15, 2016No Comments

This is a pretty basic no thrills back-to-top button written for WordPress. You can use this on a theme in your functions.php or, as I’ve implemented on MultiSite, as a network activated plugin.

The first function is for loading the CSS style in the head. The second function loads the jQuery script and anchor in the footer.

//*** Back to Top 

function back_to_top_CSS($back_to_top_CSS) {
	
		echo '
			<style type="text/css">
				.scrollToTop{
					margin: 0 30px 20px 0;
					text-align: center;
					text-decoration: none;
					position: fixed;
					bottom: 0;
					right: 0;
					display:none;
				}
				.scrollToTop:hover{
					text-decoration:none;
				}
			</style>';
}
	add_action ('wp_head', 'back_to_top_CSS', 999);	
			
	
	function back_to_top($back_to_top) {
	
		echo '<script type="text/javascript">
				jQuery(document).ready(function($) {

				  var visible = false;
				  //Check to see if the window is top if not then display button
				  $(window).scroll(function() {
					var scrollTop = $(this).scrollTop();
					if (!visible && scrollTop > 100) {
					  $(".scrollToTop").fadeIn();
					  visible = true;
					} else if (visible && scrollTop <= 100) {
					  $(".scrollToTop").fadeOut();
					  visible = false;
					}
				  });

				  //Click event to scroll to top
				  $(".scrollToTop").click(function() {
					$("html, body").animate({
					  scrollTop: 0
					}, 800);
					return false;
				  });

				});
			</script>
			
			<a href="#" class="scrollToTop"><i class="fa fa-arrow-up"></i> Top</a>';
	}
	add_action ('wp_footer', 'back_to_top', 999);	

Contact us to learn more about Adopt the Web for your business

Author Jarod Thornton

More posts by Jarod Thornton