Created
April 13, 2014 14:58
-
-
Save kezabelle/10587533 to your computer and use it in GitHub Desktop.
Hacking out a simple "return to top"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(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