Recently, I've noticed that my code looks so ugly because there were a bunch of functions and global variables. So, I started reading a little bit about design patterns. Now I come with something that's working for me, but I am not sure if it's good practice.
Anyway, I would like you to take a look at the code and tell me what can I improve. I'd also like to know a better way to start using modular pattern in JavaScript. Finally, I'd like suggestions on material for learning about modular pattern and JavaScript.
var responsiveModule = {
settings: {
device: false,
button: $(".responsive-btn"),
target: $("nav ul"),
mobileClass: "toggle-menu",
bgImage: '<img class="background-image" src="img/background.jpg" alt="">',
bgImageSelector: $(".background-image"),
windowWidth: $(window).width(),
},
init: function(){
responsiveModule.checkDevice();
responsiveModule.replaceImages();
responsiveModule.bindFunctions();
responsiveModule.listenResize();
},
checkDevice: function(){
if(this.settings.windowWidth > 992){
this.settings.device = "desktop";
} else {
this.settings.device = "mobile";
}
},
bindFunctions: function(){
var buton = this.settings.button,
muelleBtn = this.settings.muelleBtn;
buton.on("click touchstart", function(e){
e.preventDefault();
responsiveModule.animateMenu(responsiveModule.settings);
});
},
animateMenu: function(settings){
var device = settings.device,
target = settings.target,
mobileAnimation = settings. mobileClass;
if(device == "mobile"){
target.toggleClass(mobileAnimation);
}
},
replaceImages: function(){
var bgContainer = $("#main-content"),
bgImage = responsiveModule.settings.bgImage,
device = responsiveModule.settings.device,
backgroundSelector = $(".background-image");
if(device == "desktop" && backgroundSelector.length == 0){
bgContainer.append(bgImage);
}else if(device == "mobile" && backgroundSelector.length == 1){
backgroundSelector.remove();
}
},
listenResize: function(){
$(window).on("resize", function(){
responsiveModule.checkDevice();
responsiveModule.replaceImages();
responsiveModule.settings.windowWidth = $(window).width();
});
}
}
var tooltipModule = {
settings: {
tooltipState: false
},
init: function(){
tooltipModule.bindUIfunctions();
},
bindUIfunctions: function(){
var device = responsiveModule.settings.device;
if(device == "mobile"){
$(".ship").on("click", function(e){
e.preventDefault();
tooltipModule.manageTooltip(e);
});
}else{
$(".muelle-item").addClass("desktop");
}
},
manageTooltip: function(e){
var tooltip = $(e.currentTarget).next(),
tooltips = $(".tooltip");
tooltips.removeClass("display");
tooltip.addClass("display");
}
}
$(document).on("ready", function(){
responsiveModule.init();
tooltipModule.init();
});