Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS one-click Toggle (not two clicks) - default value of toggled element

Why here we need to click two times (http://jsfiddle.net/xL8hyoye/4/):

html:

<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo">This is foo</div>

css: #foo {display: none;}

js:

function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'none')
      e.style.display = 'block';
   else
      e.style.display = 'none';
}

When here only by one click text disappears (http://jsfiddle.net/xL8hyoye/5/):

html:

<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo" style='display:none'>This is foo</div> <!-- add display style here -->

css: <!-- delete ccs here -->

js:

function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'none')
      e.style.display = 'block';
   else
      e.style.display = 'none';
}
like image 277
Artem.Borysov Avatar asked Jul 12 '15 21:07

Artem.Borysov


1 Answers

Check if the style.display property is empty

    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block' || e.style.display == '')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo">This is foo</div>
like image 173
Bartłomiej T. Listwon Avatar answered Oct 18 '22 02:10

Bartłomiej T. Listwon