Friday, April 16, 2010

Show/Hide HTML div tags using JavaScript

I'm here giving a simple way to show or hide a given content in a HTML file using JavaScript dynamically. Here, I'm showing a way to hide a text by click of a button. When clicked first, it will hide the content and clicking again will show it.
The code is this:
<script type="text/javascript">
function showHide(divId){
    var theDiv = document.getElementById(divId);
    if(theDiv.style.display=="none"){
        theDiv.style.display="";
    }else{
        theDiv.style.display="none";
    }   
}
</script>

<input type="button" onclick="showHide('hidethis')" value="Test It"> 
<div id="hidethis" style="">
<h1>TEST ME!</h1>
</div>
 What is given above is one JavaScript method called showHide(divId) a button to test and the text content to be tested. See, I've given an unique ID to the div tag and kept 'style' empty. Clicking the button will change the style to style="display:none;" hiding the content. You can test this pasting the code in to a HTML file and opening it.  Each time you click, "Test It" button, it will show/hide the "TEST ME!" text.

This can be used to show/hide any thing in a given page such as tables, paragraphs, divisions etc. For, tags except div, just put them inside a div tag and do as said above.

5 comments: