Wednesday, March 19, 2008

[CSS, Javascript] How to make your <DIV> disappear


This is a quick how to for beginners.
I'll show you how to make a DIV element disapper using a button, like in this way:

This div will disapper!!!

This is done changing the class attribute of the selected DIV, as is done in the following javascript function.

<script type="text/javascript">

function hideDiv()

{

var isIE = (window.ActiveXObject)?true:false;

var attributeClass = (isIE)?"className":"class";

var element = document.getElementById("hiddenDiv");

if(element==null)

return;

if(element.getAttribute(attributeClass)=="hidden")

element.setAttribute(attributeClass, "visible");

else

element.setAttribute(attributeClass, "hidden");

}

</script>


This won't work without the definitions of the CSS classes used and the button that send the event onClick:

<STYLE>

.hidden{ display:none; }

.visible{}

</STYLE>



<input type="button" onClick="javascript:hideDiv();" value="hide"/>



<div id="hiddenDiv" >This div will disapper!!!</div>


Actually the .visible class is empty, because by default an element will be visible, so there is no need to specify that it should be visible: this is needed just to override the .hidden class.
You can use the hideDiv method with each control you wish to use that can launch an event (an hyperlink, an image, ...).

Besides, you can use also another CSS attribute, the visibility attribute; this simply makes the entity invisible/visibile, but it still occupies its space: that's why you need to insert manually a zero width and height, like in this way:
.hidden{ visibility:none; width:0px; height:0px;}
.visible{visibility:visible; }


And that's all!
See ya!

1 comment:

Unknown said...

You pull old tricks, but you do it in a cool way. You're the king of DHTML