Back-to-Top (JQuery)

by Matthew Schenker

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="content">
  <p>This is just a bunch of content.</p>
</div>
<a id="toTop">Back to top</a>

CSS

.content {
  height: 2000px;
}

#toTop {
  padding: 5px;
  background: #ccc;
  color: #fff;
  display: none;
  cursor: pointer;
}

JavaScript

$(window).scroll(function() {
  if ($(this).scrollTop()) {
    $('#toTop').fadeIn();
  } else {
    $('#toTop').fadeOut();
  }
});

$("#toTop").click(function() {
  $("html, body").animate({
    scrollTop: 0
  }, 1000);
});