xbase-2.x-dev/js/libraries/jquery.scrolltotop.js
js/libraries/jquery.scrolltotop.js
;(function($, window, document, undefined) {
'use strict';
var pluginName = 'scrollToTop';
var defaults = {
showAfterScrollTop: 0,
visibleClass: 'scroll-to-top--visible'
};
function Plugin(element, options) {
this.element = element;
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
$.extend(Plugin.prototype, {
/**
* Plugin init.
*/
init: function() {
var pluginInstance = this;
var $element = $(pluginInstance.element);
$element.on('click', function (event) {
window.scrollTo({
top: 0,
behavior: 'smooth',
});
event.preventDefault();
});
var scrollTimer;
$(document).on('scroll', function () {
if (scrollTimer) {
clearTimeout(scrollTimer);
}
scrollTimer = setTimeout(function() {
pluginInstance.check();
}, 20);
});
pluginInstance.check();
},
/**
* Show/hide element.
*/
check: function () {
var pluginInstance = this;
var $element = $(pluginInstance.element);
var viewportHeight = $(window).height();
var windowScrollTop = $(window).scrollTop();
// Show
if (windowScrollTop > this.settings.showAfterScrollTop) {
if (!$element.hasClass(this.settings.visibleClass)) {
$element.addClass(this.settings.visibleClass);
}
}
// Hide
else {
if ($element.hasClass(this.settings.visibleClass)) {
$element.removeClass(this.settings.visibleClass);
}
}
},
});
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options));
}
});
};
})(jQuery, window, document);
