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>
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?
source to share
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>
source to share
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"
).
source to share