Artem.Borysov
Artem.Borysov

Reputation: 1041

JS Toggle (display) text the simplest way

I'm trying toggle to change visibility(display) the text in next way http://jsfiddle.net/xL8hyoye/ . It doesn't work, but should work.

HTML code here:

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

JS code here:

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

(code from this source http://blog.movalog.com/a/javascript-toggle-visibility/)


Solved when replacing :

function toggle_visibility(id) {

By :

toggle_visibility = function(id) {

(thanks to Zakaria Acharki).

Reason of this is visible variable area and, in first case - JSFiddle extern libraries settings(after set no library you need to set 'No wrap in head'). As amit.rk3 said here the similar theme

Inline event handler not working in JSFiddle

And here the proof(js and html code were not changed, only 'No wrap in head' settings) http://jsfiddle.net/xL8hyoye/3/

Upvotes: 1

Views: 801

Answers (2)

Bartłomiej T. Listwon
Bartłomiej T. Listwon

Reputation: 844

You need to set the initial CSS display value of the div element (by default it is set to block, but not accessible to JS).

    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          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" style="display: block;">This is foo</div>

or check if style.display 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>

Upvotes: 1

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Update your function declaration, See the working Fiddle :

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

Upvotes: 2

Related Questions