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.

7 comments:

  1. Thanks so much for this code!!
    This was just what i needed.You made my day..

    ReplyDelete
  2. this show and then hide but i need hide and then show

    ReplyDelete
    Replies
    1. you should change css and js code .... like this
      display:none; for div that you want hide first and

      function showHide(divId){
      var theDiv = document.getElementById(divId);
      if(theDiv.style.display=="block"){
      theDiv.style.display="";
      }else{
      theDiv.style.display="block";
      }
      }

      Delete
    2. you should change the css first like this .... display:none; for div that u want to hide
      and js should like this
      function showHide(divId){
      var theDiv = document.getElementById(divId);
      if(theDiv.style.display=="block"){
      theDiv.style.display="";
      }else{
      theDiv.style.display="block";
      }
      }

      Delete
  3. can we do that in class tag and display them
    $("a.cabinid").click(function(){
    $("#airfilter").hide();
    $("#oilfilter").hide();

    ReplyDelete