Skip to content

Instantly share code, notes, and snippets.

@gregrickaby
Created December 2, 2015 17:49
Show Gist options
  • Save gregrickaby/3c10c0ac9e4dfbd7cff6 to your computer and use it in GitHub Desktop.
Save gregrickaby/3c10c0ac9e4dfbd7cff6 to your computer and use it in GitHub Desktop.
WDS Javascript Back To Top
/**
* Back To Top.
*/
window.Back_To_Top = {};
( function( window, $, that ) {
// Private variables.
var minWidth = 768;
var minHeight = 200;
// Constructor.
that.init = function() {
that.cache();
if ( that.meetsRequirements ) {
that.bindEvents();
}
};
// Cache all the things.
that.cache = function() {
that.$c = {
window: $( window ),
backToTopWrap: $( '.btt-area' ),
htmlBody: $( 'html, body' ),
};
};
// Combine all events.
that.bindEvents = function() {
that.$c.window.on( 'scroll', that.displayBackToTop );
that.$c.backToTopWrap.on( 'click', that.animateScroll );
};
// Do we meet the requirements?
that.meetsRequirements = function() {
return that.$c.backToTopWrap.length && minWidth <= that.$c.window.width();
};
// Fade the Back To Top link.
that.displayBackToTop = function() {
// If we've scrolled down at least 200 pixels, fade in.
if ( that.$c.window.scrollTop() > minHeight ) {
that.$c.backToTopWrap.fadeIn( minHeight );
// Otherwise, fade out.
} else {
that.$c.backToTopWrap.fadeOut( minHeight );
}
};
// Animate the scroll back up.
that.animateScroll = function(e) {
e.preventDefault();
that.$c.htmlBody.animate({scrollTop: 0}, 300);
};
// Engage!
$( that.init );
})( window, jQuery, window.Back_To_Top );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment