Scroll to top

Scroll to top button fades in during scroll and fades out when at top of the page.

by James Hooper

HTML

<div id="back_to_top">
  UP
</div>

CSS

#back_to_top {
  bottom: 20px;
  right: 10px;
  width: 35px;
  height: 42px;
  background-color: #000;
  position: fixed;
}

html {
  overflow: scroll;
  height: 5000px;
}

JavaScript

var resizeTimer;
	var windowWidth = $(window).width();
	var windowHeight = $(window).height();

	var resizeFunction = function() {

	  var pageWidth = $('.inner').width();
	  var backToTop = (((windowWidth - pageWidth) / 2) + 35);
	  var documentHeight = parseInt($(document).height());
	  var showScrollBtn = (documentHeight - windowHeight);
	  var scrollBtnFix = 50;

	  $('#back_to_top').css("right", backToTop);

	  $(window).scroll(function() {
	    if ($(window).scrollTop() < scrollBtnFix) {
	      //console.log('FIX');
	      $('#back_to_top').css("position", "absolute");
	      $('#back_to_top').css("bottom", "20px");
	      $('#back_to_top').css("right", "35px");

	    } else {
	      //console.log('UNFIX');
	      $('#back_to_top').css("position", "fixed");
	      $('#back_to_top').css("bottom", "20px");
	      $('#back_to_top').css("right", backToTop);
	    }
	  });

	  //console.log(documentHeight + 'documentHeight');
	  //console.log(footerheight + 'footerheight');
	  //console.log(scrollButtonOffset + 'scrollButtonOffset');
	  //console.log ($(window).height() + 'windowHieght');
	  //console.log (scrollBtnFix + 'scrollBtnFix');
	  //console.log (backToTop);


	  //console.log(footerPosition.top + 'footerPosition');

	  //$(window).scrollTop(documentHeight - (footerPosition.top + windowHeight));
	  //$(window).scrollTop(footerPosition.top - windowHeight);

	}

	$('#back_to_top').click(function() {
	  $('html, body').animate({
	    scrollTop: 0
	  }, 700);
	  return false;
	});

	$(window).scroll(function() {

	  var amountScrolled = 300;

	  if ($(window).scrollTop() > amountScrolled) {
	    $('#back_to_top').fadeIn('fast');
	  } else {
	    $('#back_to_top').fadeOut('fast');
	  }

	  //console.log($(document).scrollTop());

	});