Code Snippet
Toggle (Show/Hide) Element
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>Inline usage:
<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo">This is foo</div>
What is this? … Looks like it was scratched off a bathroom wall somewhere…
Where’s the function statement? And how about using var for declaring local variables?
I think it was a bad copy and paste job compounded. Fixed it up a bit.
Thanks for fixing it Chris. :)
the only problem i have with it is what i have to click the link twice the first time to make it disappear.
Why does this need 2 clicks? I’m new at javascript, and this is driving me crazy!
This function works better!
function toggle_visibility(id) {var e = document.getElementById(id);
e.style.display = ((e.style.display!='none') ? 'none' : 'block');
}
I feel that the usage of display:none should be avoided if that is possible. Some versions of Webkit based browsers consider display:none like the element no longer a part of the DOM.
Instead you can have a CSS class like the following one:
.hidden{
position: absolute;
left: -9999px;
top: -9999px;
visibility: hidden;
}
After using JavaScript code you can add or remove the class name if you wish to hide or show the element respectively.
The advantage is the element will be present in the DOM all the time but in a non-visible manner if it is in hidden state.
DigWP
A book and blog co-authored by Jeff Starr and myself about the World's most popular publishing platform.
Quotes on Design
Design, like Art, can be an elusive word to define and an awfully fun thing to have opinions about.
HTML-Ipsum
One-click copy to clipboard access to Lorem Ipsum text that comes wrapped in a variety of HTML.
Bookshelf
Hey Chris, what books do you recommend? These, young fertile mind, these.