June 1, 2007
Hiding and Showing
The visibilty of an element is a powerful tool that can be used in JavaScript to create everything from animations and effects to fast templating. More importantly, however, it can also be used to quickly hide an element from view, providing users with some basic user interaction capabilities.
Within CSS there are two different ways of effectively hiding an element from view; both have their benefits but can provide unintented consquences, depending on how you use them:
The visibility property toggles whether an element is visible or not, while still leaving its normal flow properties intact. The visibility property has two values: visible (default) and hidden.
The display property provides more options to a developer for controlling the layout of an element. The options for it vary between inline, block and none (which completely hides an element from the document. The result of setting a display property of an element looks exactly the same as if you had just removed the element from the document.
function hideshow() { var elem = document.getElementById("hideshow"); if (elem.style.display == 'none') { elem.style.display = 'block'; } else { elem.style.display = 'none'; } }
Since we are separating behavior from presentation we should make our link behave like a link too.
link.onclick = function () { hideshow(); } link.onmouseover = function () { this.style.cursor = 'pointer'; }
Put this all together into a simple example. Download the code (.zip) if you want as well.
