Simlpe scroll to top

A simlpe scroll to top to use on your webpage.

by Martin Emanuelsson

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<p>Welcome - scroll down 100px to display button</p>
<a href="#" class="scrollToTop">Scroll to top</a>

CSS

body {
  height: 2000px;
}

.scrollToTop {
  width: 50px;
  height: 50px;
  padding: 10px;
  text-align: center;
  color: #FFF;
  text-decoration: none;
  position: fixed;
  bottom: 20px;
  right: 20px;
  display: none;
  background: #000;
}

.scrollToTop:hover {
  text-decoration: none;
  color: #F2F2F2;
  background: #333;
}

JavaScript

$(document).ready(function() {
  'use strict';

  //* Check to see if the window is top if not then display button
  $(window).scroll(function() {
    if ($(this).scrollTop() > 100) { // <-- Set distance from top to view scroll
      $('.scrollToTop').fadeIn();
    } else {
      $('.scrollToTop').fadeOut();
    }
  });

  //* Click event to scroll to top
  $('.scrollToTop').click(function() {
    $('html, body').animate({
      scrollTop: 0
    }, 800); // <-- Set speed
    return false;
  });

  console.log('Scrollbar is ready.');
});