Skip to content

Instantly share code, notes, and snippets.

@kezabelle
Created April 13, 2014 14:58
Show Gist options
  • Save kezabelle/10587533 to your computer and use it in GitHub Desktop.
Save kezabelle/10587533 to your computer and use it in GitHub Desktop.
Hacking out a simple "return to top"
;(function($, window, document, undefined) {
var totop;
var show_at;
var already_shown;
var didscroll;
var update_didscroll;
var maybe_should_display;
var move;
/*
* Skips back to the beginning of the document
*/
move = function(evt) {
var change_hash;
evt.preventDefault();
change_hash = function() {
return window.location = '#moved-' + (+new Date).toString();
};
return $(document.body).stop().animate({scrollTop: 0}, 500, 'linear', change_hash);
};
totop = $('.return-to-top').eq(0);
totop.bind('click', move);
/*
* Decides whether or not the return to top link should be visible
*/
show_at = totop.outerHeight();
already_shown = false;
function should_display() {
var current_pos;
var should_fadein;
var should_fadeout;
current_pos = $(window).scrollTop();
should_fadein = current_pos > show_at && already_shown === false;
if (should_fadein === true) {
totop.fadeIn(500);
already_shown = true;
return true;
}
should_fadeout = current_pos < show_at && already_shown === true;
if (should_fadeout === true) {
totop.fadeOut(500);
already_shown = false;
return false;
}
}
$(document).ready(should_display);
// see http://ejohn.org/blog/learning-from-twitter/
didscroll = false;
update_didscroll = function() {
didscroll = true;
};
$(window).scroll(update_didscroll);
maybe_should_display = function() {
if (didscroll === true) {
didscroll = false;
return should_display.call(this);
}
return false;
};
setInterval(maybe_should_display, 500);
})(jQuery, window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment