简体   繁体   中英

Add onclick with JavaScript and Show/Hide a div using a module pattern

I am trying to create a JavaScript Module using the pattern I found here .

I would like to add the onclick event to the <a> element with JavaScript. Each click of the <a> element should hide or show the content div.

Here is a Fiddle to what I have so far: http://jsfiddle.net/66aKc/

Here is the HTML I have:

<a href="#" id="clickHere">Click here to toggle visibility</a>
<div id="foo">This is foo</div>

Here is the CSS I have:

#foo {display:none;}

Here is the JavaScript I have:

var s;
ShowHideWidget = {

  settings : {
    clickHere : document.getElementById('clickHere'),
    foo       : document.getElementById('foo')
  },

  init : function() {
    s = this.settings;
    this.bindUIActions();
  },

  bindUIActions : function() {
    s.clickHere.onclick =
        ShowHideWidget.toggleVisibility(s.foo);
  },

  toggleVisibility : function(id) {
    if(id.style.display == 'block') {
      id.style.display = 'none';
    } else {
      id.style.display = 'block';
   };
  }

};

(function() {
  ShowHideWidget.init();
})();

I am not sure why this does not work.

when you assign your onclick handler you are executing the function, not attaching it as a handler, so onclick becomes the return of toggleVisibility which is null.

Try:

var s;
ShowHideWidget = {

  settings : {
    clickHere : document.getElementById('clickHere'),
    foo       : document.getElementById('foo')
  },

  init : function() {
    s = this.settings;
    this.bindUIActions();
  },

  bindUIActions : function() {
    s.clickHere.onclick = function() {
        ShowHideWidget.toggleVisibility(s.foo);
    };
  },

  toggleVisibility : function(id) {
    if(id.style.display == 'block') {
      id.style.display = 'none';
    } else {
      id.style.display = 'block';
   };
  }

};

(function() {
  ShowHideWidget.init();
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM