Wednesday, March 15, 2006

Display and Hide DIVs Using Javascript and CSS

Suppose I have some text within <div id="div1"></div> tags, it's easy to display and hide this block of text with the help of some Javascript code and CSS.

To hide the block of text, do the following:

<script language="javascript">
document.getElementById('div1').style.display = 'none';
</script>

To display the block of text, just remove the word 'none' from the code above as follows:

<script language="javascript">
document.getElementById('div1').style.display = '';
</script>

To further extend this capability, we can put the code above in a Javascript function, which can be called using the OnClick event. This can be easily done with a form checkbox as follows:

<input type="checkbox" id="CheckBoxID" OnClick="ShowHideDIV();">

function ShowHideDIV()
{
var blnCheckbox = document.getElementById('CheckBoxID')
if(blnCheckbox.checked)
{
document.getElementById('div1').style.display = 'none';
}
else
{
document.getElementById('div1').style.display = '';
}
}

No comments: