Modular Javascript Sliding Menu [Solved]

Modular Javascript Sliding Menu [Solved]
0

#1

I’m practising modular javascript and i’m trying to convert this jQuery code to modular but it’s not working. I’m relatively new to this so i’m not sure what the problem is.

This is the original code.

var main = function() {
    $('.icon-menu').click(function() {
        $('.menu').animate({
            left: '0px'
        }, 200);

        $('body').animate({
            left: '285px'
        }, 200);
    });
    $('.icon-close').click(function() {
        $('.menu').animate({
            left: '-285px'
        }, 200);

        $('body').animate({
            left: '0px'
        }, 200);
    });
  
};

$(document).ready(main);

This is my conversion to modular.

(function () {

var menu = {
    init: function () {
        this.cacheDom ();
        this.bindEvents ();
    },
    cacheDom: function () {
        this.$mh = $('#menuHolder');
        this.$iMenu = this.$mh.find('.icon-menu');
        this.$iClose = this.$mh.find('.icon-close');
        this.$menu = this.$mh.find('.menu');
        this.$body = this.$mh.find('body');
    },
    openMenu: function () {
        this.$menu.animate({left: "0px"}, 200);
        this.$body.animate({left: "285px"}, 200);
    },
    closeMenu: function () {
        this.$menu.animate({left: "-285px"}, 200);
        this.$body.animate({left: "0px"}, 200);
    },
    bindEvents : function () {
        this.$iMenu.on("click", this.openMenu.bind(this));
        this.$iClose.on("click", this.closeMenu.bind(this));
    }
    
};

menu.init;
  
})();

Cheers for any help :slight_smile:


#2

Never mind, sorry I miss the parentheses off menu.init();

(Also needed to change

this.$body = this.$mh.find('body');

to

this.$body = $('body');)