Chittolina
Chittolina

Reputation: 235

JavaScript: Hide and Show Menu Class

var Menu = function() {
    state = 0;
}
Menu.prototype.click = function() {
    if (this.state == 1) {
        $(document).ready(function(){
            $("#collapse-menu").click(function(){
                $("#list-navbar").show(500);
                this.state = 0;
            });
        });
    } else {
        $(document).ready(function(){
            $("#collapse-menu").click(function(){
                $("#list-navbar").hide(500);
                this.state = 1;
            });
        });
    }
}

How can I instantiate the class on the page load and just call the function click onclick event, keeping the class instantiated?

Upvotes: 2

Views: 72

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206008

var Menu = function() {
  this.state = 0;
};

Menu.prototype.click = function() {
  var that = this;   // our Menu object

  $("#collapse-menu").click(function(){
    that.state ^= 1; // Toggles 1,0,1... values
    $("#list-navbar")[that.state?"hide":"show"](500);
  });
};


jQuery(function( $ ) { // DOM ready here

  var m = new Menu();  // New Menu instance
  m.click();           // init clicks on #collapse-menu

});

jsBin demo

about ^ as toggler: https://stackoverflow.com/a/22061240/383904

Upvotes: 2

Related Questions