I am trying to practice different module patterns. Below is IIFE pattern for a scroll function that can be used for different elements in different pages (not sure this is the right pattern for the purpose).
My question is 1. how to replace the config = {} options outside IIFE module? 2. I name every single functions, not sure if this is an overkill or suggested way in write this kind of code. 3. What would be a better module pattern for the purpose?
;(function($, ScrollToTop, undefined) {
'use strict';
var clickedElem = $('[data-scroll]');
var config = {
scrollDistance: 500,
speed: 300
};
var _scrollToTargetAnimation = function () {
$('body').animate({
scrollTop: $($(this).data('scroll')).offset().top
}, config.speed);
return false; //stop bubbling
};
var _showHideAnimation = function () {
if ($(this).scrollTop() > config.scrollDistance) {
clickedElem.fadeIn(config.speed);
} else {
clickedElem.fadeOut(config.speed);
}
};
ScrollToTop.showHide = function() {
if ($('.top-bar').length) return;
$(document).scroll( _showHideAnimation );
};
ScrollToTop.clickBtn = function() {
clickedElem.on('click', _scrollToTargetAnimation );
};
ScrollToTop.init = function (config) {
$.extend(this.config, config);
ScrollToTop.showHide();
ScrollToTop.clickBtn();
};
})(jQuery, window.ScrollToTop = window.ScrollToTop || {});
$(function() {
config = {
scrollDistance: 500,
speed: 300
};
ScrollToTop.init(config);
});