Skip to content

Instantly share code, notes, and snippets.

@rlemon
Last active September 7, 2016 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rlemon/4453414 to your computer and use it in GitHub Desktop.
Save rlemon/4453414 to your computer and use it in GitHub Desktop.
"Return to top" button as a plugin with some slick defaults.

#Usage

$.mcToppy({
  text: 'Get back up there!',
  speed: 1000,
  css: { fontFamily: 'Arial' }
});

You can over-ride any of the defaults, however if not specified the defaults will be used.

If you want the position to be at the top, you need to set the 'top' and then clear the 'bottom' css rules.

Demo here

$.mcToppy = function (options) {
var btn = $('<button></button>'),
defaults = {
css: {
position: 'fixed',
bottom: '16px',
right: '16px',
backgroundColor: '#FFF',
color: '#444',
padding: '4px 6px',
borderRadius: '4px',
display: 'none'
},
text: 'Top',
speed: 500,
callback: undefined
};
options = options || {};
options = $.extend({}, defaults, options);
btn.css(options.css).text(options.text).on('click', handle_click).appendTo('body');
$(window).on('scroll', handle_scroll);
function handle_scroll() {
if ($(this).scrollTop() != 0) {
btn.fadeIn('fast');
return;
}
btn.fadeOut('fast');
}
function handle_click() {
$('html,body').animate({
scrollTop: 0
}, options.speed).promise().done(options.callback);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment