Show / hide element by ID

function showhide(id) {
  obj = document.getElementById(id);

  if (obj.style.display == 'none' || obj.style.display == null)
    obj.style.display = 'block';
  else
    obj.style.display = 'none';
}
      

#stuff {
  display: none;
}
      

<a href="#" onclick="showhide('stuff'); return false;">Click Me</a>

<div id="stuff">
  secret stuff
</div>
      

Run codeHide result


This view works but requires two clicks. It seems that he cannot detect that condition null

.

Apparently if I change the condition to this it works:

if (obj.style.display == 'block')
        obj.style.display  = 'none';
else
        obj.style.display  = 'block';

      

Now my question is, what is wrong with the first condition?

+3


source to share


3 answers


If the display of an element is specified in a CSS rule, you need to get its computed style. What you are doing will work if you replace the inline style with a div.



function showhide (id)
{
    obj = document.getElementById(id);
    var displayStyle = obj.currentStyle ? obj.currentStyle.display :
                          getComputedStyle(obj, null).display;
    if (displayStyle == 'none' || displayStyle == null)
        obj.style.display  = 'block';
    else
        obj.style.display  = 'none';
}
      

#stuff { display:none; }
      

<a href="#" onclick="showhide('stuff'); return false;">Click Me</a>

<div id="stuff">
    secret stuff
</div>
      

Run codeHide result


+1


source


Ask yourself: at what point obj.style.display

ever null

? If you do register it on the console, you get ""

.

In your first code, obj.style.display

there is neither "none"

, nor ""

, so the script is executed else

: itll will be set to "none"

. It is no longer displayed, but only because of the CSS rule, not a direct property style

on the element itself.



The second code works because it means ""

both "none"

behave the same and "block"

behave differently, which it actually does (if you only use "none"

and "block"

).

0


source


You can set the display attribute of an element directly rather than using CSS, so:

<div id="stuff" style="display:none">
  secret stuff
</div>

      

and get rid of

#stuff { display:none; }

      

Then your first example (no null check required) will work.

0


source







All Articles