Bootstrap Float to Top Button

Facebooktwittergoogle_plusredditpinterestlinkedintumblrFacebooktwittergoogle_plusredditpinterestlinkedintumblr

For some time this website has been styled using the Bootstrap framework, and I have been meaning to investigate how to make a Bootstrap Float to Top Button. It should be quite easy; a simple snippet of javascript and a small amount of CSS. You  will need to make a javascript file (I called mine bs-back-to-top.js) containing this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$(document).ready(function(){
      $('body').append('<div id="toTop" class="btn btn-info"><i class="fa fa-arrow-up"></i>Back to Top</div>');
    	$(window).scroll(function () {
			if ($(this).scrollTop() != 0) {
				$('#toTop').fadeIn();
			} else {
				$('#toTop').fadeOut();
			}
		}); 
    $('#toTop').click(function(){
        $("html, body").animate({ scrollTop: 0 }, 600);
        return false;
    });
});

Note that this uses Font Awesome for the icon on the button, so you will need to have Font Awesome already loading to your site pages. To get WordPress to call this javascript file, you are going to have to roll your sleeves up and do a bit of coding. For beginners this will be hard. If you know WordPress at all, you will not be using a theme directly, but instead you will be using a child theme. This is especially so if you are using a theme framework, such as the one I use; Ultimatum Theme. Assuming that you already have a child theme, it will have a file called functions.php in the theme folder. Into that you will need a few lines of script like this:

1
2
3
4
5
function bs_back_to_top() {
  wp_register_script( 'bs-back-to-top', get_stylesheet_directory_uri() . '/js/bs-back-to-top.js', array('jquery'), '1.0.0', true );
  wp_enqueue_script( 'bs-back-to-top' );
}
add_action( 'wp_enqueue_scripts', 'bs_back_to_top', 99 );

You should notice that I stored the javascript file in its own js sub-folder in the child theme folder. Hopefully, you already have a custom stylesheet for your child theme (mine is called custom-style.css and sits in a css folder inside the child theme folder, and is already enqueued, see this post for more details on a custom css file and the functions.php file), this is the new css to add to it:

1
2
3
4
5
6
7
8
#toTop{
	position: fixed;
	bottom: 95px;
	right: 40px;
	cursor: pointer;
	display: none;
}
#toTop .fa {margin-right: 5px;}

You may need to play with the bottom, right and margin right settings to suit your own needs. The result you can see on any of this site’s longer pages. I hope you managed to follow this short tutorial. Bye for now.

Categories: WordPress.