Need to hide, then show some HTML content? Maybe you need to hide some text until the user explicity asks for it? In any case, here’s a really simple way to do it:
<script type="text/javascript">
function toggle(element) {
document.getElementById(element).style.display = (document.getElementById(element).style.display == "none") ? "" : "none";
}
</script>
Click to toggle insightful quote…
In Code We Trust
Add this to your HTML (or preferrably your globally included JavaScript file):
<script type="text/javascript">
function toggle(element) {
document.getElementById(element).style.display = (document.getElementById(element).style.display == "none") ? "" : "none";
}
</script>
Add this to where you want to show or hide stuff:
<a href="javascript:toggle('secret')">Click to toggle…</a>
<div id="secret" style="display: none;">
Top Secret!
</div>
[Update]: Thanks to Jeff Minard for drastically optimising the code.
Ternary operators ftw:
function toggle(element) {
document.getElementById(element).style.display = (document.getElementById(element).style.display == "none") ? "" : "none";
}
Ooh, nice! I’ve been meaning to learn that syntax for ages. Thanks.
what if JS is off? Do you have some workaround to get hidden content accessiblet?
And thanks for the snippet anyway, we love it.
Actually I do.
If you want it to degrade gracefully, leave out the ‘ style=”display: none;”‘ from the HTML, and instead add the following:
But you have to add the following function to the JS snippet:
function hideOnLoad(element) { document.getElementById(element).style.display = "none"; }That way, the box will only become hidden in the first place, if you do have JS enabled. If you do have JS, and it is hidden, the toggle will also work. I actually do that on the frontpage of noscope .
Oh this is smashing, thanks so much. Let us to kill as a JS users and those who has it off at once.
I’ve used a similar type of js toggle of css for a web based application I was having to do design and CSS/html coding. It works very well.
Doesn’t work on my iPhone.
Excellent. Thank you for this! It will come in useful.
This is really wonderful, I use this in my menu arrows and I had first seen it in fauna’s comment html syntax guide.
You can simplify the code yet a little more. Please check out the code I posted earlier this year for toggling (show/hide) all combo boxes of a page:
http://kaisar-haque.blogspot.com/2007/05/javascript-yet-another-toggle-showhide_03.html
Cheers!
-Kaisar
Ah brilliant, this is perfect, just what I needed for my site.
Thanks!
Fort Lauderdale Florida, 33301. USA
Merci mil fois merci!
Gracias, funciona perfecto!
Brilliant script – why can’t all scripts be this good and this simple?